Am new to Spring. Followed online resources and implemented factory pattern without @Component annotation using ServiceLocatoryFactory, it is working fine.
But How to implement annotation(without context xml) based factory pattern by using @Component without using switch case or if/else conditions. I followed this link and implemented like below:
public interface Printer {
public String helloPrinter();
}
@Component
@Qualifier("PrinterOne")
public class PrinterOne implements Printer {
public String helloPrinter() {
return "PrinterOne";
}
}
@Component
@Qualifier("PrinterTwo")
public class PrinterTwo implements Printer {
public String helloPrinter() {
return "PrinterTwo";
}
}
public interface PrinterFactory {
public Printer getPrinter(String printerName);
}
@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();
}
}
But i am getting below error:
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)
As i am new to spring am not able to find the problem, Can anyone tell me where i am going wrong? Thanks in advance.
Aucun commentaire:
Enregistrer un commentaire