我試圖在Java Spring引導應用程序中創建工廠方法。但不是手動實例化一個對象,我想從DI容器中獲取它。那可能嗎?從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
}
}
收到錯誤「無類型的符合條件的bean的com.test.mp.service.PaymentServiceImplA「可用」時的getBean方法被調用。
@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);
}
}
它應該是可用的,因爲?我沒有看到「@ Service」,所以它不會被檢測到。另外,我建議編寫自己的'@ Conditional'規則(取決於條件,你甚至可以使用其中一個現有的規則) –
我想使用DI容器,因爲實現類需要大量的這些對象反過來有很多依賴關係,所以我不想手動實例化它們,我將檢查@Conditional規則,謝謝! – Baga
這與那些沒有'@ Service'有關嗎?我強烈建議看看有條件的規則(這些規則也可以應用於帶註釋的類) –