簡體   English   中英

Spring 引導:class 找不到@Service bean bean

[英]Spring Boot: class with @Service bean bean not found

我有多個實現 class BaseService@Service class

Controller class 中,我想根據參數調用Service class (實現BaseService

我在Utils中使用 function 並從Controller class 調用它

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 class 有一個@Service注釋

如果我使用Controller class 中的構造函數調用TestService

@Autowired
public TestController(TestService service){
   this.service = service;
}


service.callMethod(); //This works!!

但是如果我使用Util class 調用實例,它會給我No such bean as TestService available

您的AnnotationConfigApplicationContext最初是空的。 引用文檔:“創建一個新的 AnnotationConfigApplicationContext 需要通過register(java.lang.Class<?>...)調用填充,然后手動刷新。”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM