我是春天的新手, 我使用ServiceLocatorFactoryBean实现了工厂模式,如下所示..
public interface Printer{
public void print();
}
public class Printer1 implements Printer{
@Override
public void print(){
System.out.println("printer1");
}
}
public class Printer2 implements Printer{
@Override
public void print(){
System.out.println("printer2");
}
}
和工厂界面
public interface PrinterFactory{
public printer getPrinter(String printerName);
}
我正在使用基于注释的
@Configuration
@ComponentScan(basePackage)
public class PrinterConfiguration {
@Bean
public ServiceLocatorFactoryBean createFactoryBean() {
ServiceLocatorFactoryBean factory = new ServiceLocatorFactoryBean();
factory.setServiceLocatorInterface(PrinterFactory.class);
return factory;
}
@Bean(name = "printer1")
@Scope(value=ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public Printer1 printer1Service(){
return new Printer1();
}
@Bean(name = "printer2")
@Scope(value=ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public Printer2 printer1Service(){
return new Printer2();
}
}
并且如下所示:
@Autowired
PrinterFactory printerFactory;
printerFactory.getPrinter("printer1");
低于例外:
Could not autowire field: org.test.myproject.PrinterFactory org.test.myproject.controller.MyController.printerFactory ; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.test.myproject.PrinterFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
谁能告诉我哪里出错?