我有多個@Service實作一個類的類BaseService
在一個Controller類中,我想根據一個引數呼叫一個Service類(實作)BaseService
我正在使用一個函式Utils并從Controller類中呼叫它
public final class Util {
public static BaseService getService(String num){
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.refresh();
if(num == 1){
return context.getBean(TestService.class);
}
return context.getBean(AnotherService.class);
}
}
我的TestService班級有@Service注釋
TestServiceController如果我在類中使用建構式呼叫它,則有效
@Autowired
public TestController(TestService service){
this.service = service;
}
service.callMethod(); //This works!!
但是如果我使用類呼叫實體Util,它會給我No such bean as TestService available
uj5u.com熱心網友回復:
你AnnotationConfigApplicationContext的最初是空的。參考檔案:“創建一個新的 AnnotationConfigApplicationContext 需要通過register(java.lang.Class<?>...)呼叫填充,然后手動重繪 。”
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/422673.html
標籤:
