[英]Factory method getting new instance from DI Container
我正在尝试在Java Spring启动应用程序中创建工厂方法。 但是,我不想手动实例化一个对象,而是想从DI容器中获取它。 那可能吗?
public interface PaymentService {
public Payment createPayment(String taskId);
}
public class PaymentServiceImplA implements PaymentService {
private JobService jobService;
private ApplicationService applicationService;
private UserService userService;
private WorkService workService;
@Inject
public PaymentServiceImplA(JobService jobService, UserService userService, WorkService workService,
ApplicationService applicationService) {
this.jobService = jobService;
this.applicationService = applicationService;
this.userService = userService;
this.workService = workService;
//removed other constructor injected dependencies
}
}
调用getBean方法时出现错误“没有可用的'com.test.mp.service.PaymentServiceImplA'类型的合格Bean”。
@Configuration
public class PaymentFactory {
private ApplicationContext applicationContext;
@Inject
public PaymentFactory(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Bean
public PaymentService paymentService(){
//Using getBean method doesn't work, throws error mentioned above
if(condition == true)
return applicationContext.getBean(PaymentServiceImplA.class);
else
return applicationContext.getBean(PaymentServiceImplB.class);
}
}
在配置文件中再创建两个bean之后,可以解决此问题。 即
@Bean
public PaymentService paymentServiceA(){
return new PaymentServiceImplA();
}
@Bean
public PaymentService paymentServiceB(){
return new PaymentServiceImplA();
}
返回的bean应该是:
@Bean
public PaymentService paymentService(){
if(condition == true)
return paymentServiceA();
else
return paymentServiceB();
}
是的,可以在ServiceLocatorFactoryBean的帮助下进行。 实际上,如果我们编写Factory代码以创建实现对象,则在该实现类类中,如果我们注入任何存储库或其他对象,则它将引发异常。 原因是如果用户创建了对象,则对于那些对象,spring不允许注入依赖项。 因此,最好将使用Spring的按工厂模式创建实现对象的责任赋予。 尝试使用ServiceLocatorFactoryBean
这就是我现在最终解决此问题的方式。 通过向bean方法注入实例化实现对象所需的依赖关系。
@Configuration
public class PaymentFactory {
//private ApplicationContext applicationContext;
public PaymentFactory() {
//this.applicationContext = applicationContext;
}
@Bean
public PaymentService paymentService(JobService jobService, UserService userService
, WorkService workService, ApplicationService applicationService){
if(condition == true){
return new PaymentServiceImplA(jobService, userService, workService,
applicationService);
}
else {
return new PaymentServiceImplB(jobService, userService, workService,
applicationService);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.