工厂方法从 DI 容器获取新实例

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 方法时出现错误 "No qualifying bean of type 'com.test.mp.service.PaymentServiceImplA' available"。

@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 是可能的。事实上,如果我们编写工厂代码来创建实现对象,那么在该实现中 class class 如果我们注入任何存储库或其他对象,那么它将抛出异常。原因是如果用户创建了对象,那么对于那些对象 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);
        }
    }
}