工厂方法从DI Container获取新实例

时间:2017-05-30 05:37:13

标签: java spring spring-boot dependency-injection factory-pattern

我正在尝试在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);

    }
}

3 个答案:

答案 0 :(得分:1)

这可以在配置文件中再创建两个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();

    }

答案 1 :(得分:0)

是的,可以在ServiceLocatorFactoryBean的帮助下完成。事实上,如果我们编写Factory代码来创建实现对象,那么在该实现类类中,如果我们注入任何存储库或其他对象,那么它将抛出异常。原因是如果用户是创建对象然后对于那些对象spring不允许注入依赖项。因此,更好地承担使用Spring通过工厂模式创建实现对象的责任。尝试使用ServiceLocatorFactoryBean

答案 2 :(得分:0)

这就是我现在最终解决这个问题的方法。通过使用实例化实现对象所需的依赖项注入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);
        }
    }
}