是Spring的新手。使用@Componen
跟踪在线资源并实施工厂模式而没有ServiceLocatoryFactory
t注释,它工作正常。
但是如何在不使用switch case或if / else条件的情况下使用@Component
来实现基于工厂模式的注释(没有上下文xml)。
我按照this链接进行操作,如下所示:
服务界面
public interface Printer {
public String helloPrinter();
}
实施1
@Component
@Qualifier("PrinterOne")
public class PrinterOne implements Printer {
public String helloPrinter() {
return "PrinterOne";
}
}
实施2
@Component
@Qualifier("PrinterTwo")
public class PrinterTwo implements Printer {
public String helloPrinter() {
return "PrinterTwo";
}
}
服务工厂界面
public interface PrinterFactory {
public Printer getPrinter(String printerName);
}
PrinterService
@Service
public class PrinterService {
@Autowired
private PrinterFactory printerFactory;
public Printer processPrinter(String printerName) {
Printer printer = printerFactory.getPrinter(printerName);
return printer;
}
}
配置
@Configuration
@ComponentScan(basePackages = { "com.test.factory" })
public class PrinterConfiguration {
@SuppressWarnings("rawtypes")
@Bean
public FactoryBean serviceLocatorFactoryBean() {
final ServiceLocatorFactoryBean factoryBean = new ServiceLocatorFactoryBean();
factoryBean.setServiceLocatorInterface(PrinterFactory.class);
return factoryBean;
}
@Bean(name = "PrinterOne")
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public PrinterOne printerOnePrinter() {
return new PrinterOne();
}
@Bean(name = "PrinterTwo")
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public PrinterTwo printerTwoPrinter() {
return new PrinterTwo();
}
}
控制器
@RestController
public class TestController {
@Autowired
private PrinterService printStrategyFactory;
@RequestMapping(value = "/api/test/factory/{printer_name}", method = RequestMethod.GET)
public @ResponseBody ObjectNode getPrinterValue(@PathVariable String printer_name)
throws IOException {
final ObjectMapper mapper = new ObjectMapper();
ObjectNode objectNode = mapper.createObjectNode();
System.out.println("Test");
try {
objectNode.put("Test", "test");
objectNode.put("Value", printStrategyFactory.processPrinter(printer_name).helloPrinter());
} catch (Exception exception) {
exception.printStackTrace();
String errMsg = "Exception occured while executing factory";
objectNode.put(ERROR_FIELD, String.format(errMsg, exception.toString()));
return objectNode;
}
return objectNode;
}
}
但是我得到了以下错误:
[localhost-startStop-4] ERROR org.springframework.web.context.ContextLoader - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.test.factory.autoscan.PrinterService com.test.factory.controllers.TestController.printStrategyFactory; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.test.factory.autoscan.PrinterService] 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)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:5003)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5517)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:652)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:1095)
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1960)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.test.factory.autoscan.PrinterService com.test.factory.controllers.TestController.printStrategyFactory; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.test.factory.autoscan.PrinterService] 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)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:573)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 26 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.test.factory.autoscan.PrinterService] 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)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1373)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1119)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:545)
... 28 more
由于我刚接触春天我无法找到问题,有谁能告诉我哪里出错了?提前致谢。