這篇文章主要為大家展示了“SpringBoot怎么在線程中獲取@Service Bean類”,內容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領大家一起研究并學習一下“SpringBoot怎么在線程中獲取@Service Bean類”這篇文章吧。
這個適用于沒有Spring配置文件的Springboot項目中,有配置文件的話取bean就方便多了。
下圖是我用@Service注解聲明的一個Mybatis Mapper Bean,平常在Springboot掃描配置下的類直接用
@Autowired注解依賴注入。


我現在需要在線程中使用,然而Springboot自然而然只能掃描到自己的東西 ,線程實現的Runnable接口,
1、首先創建一個配置類繼承ApplicationContextAware,取得ApplicationContext。

利用里面的getBean方法取得你想要的Bean類。

這樣你就能在線程中得到你要的Bean類了。挺坑的?。?!
注:多線程場景下,使用默認的spring自動裝配無法獲取bean對象,此方案可以從context上下文中直接獲取bean。
實現ApplicationContextAware接口;
package com.bond.match.utils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* Created with IntelliJ IDEA.
* Date: 2018/1/11 0011
* Time: 13:20
* To change this template use File | Settings | File Templates.
*/
@Component
public class ApplicationContextProvider implements ApplicationContextAware {
private static ApplicationContext context;
private ApplicationContextProvider(){}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
public static <T> T getBean(Class<T> aClass){
return context.getBean(aClass);
}
}.method()是bean對象的方法名稱
ApplicationContextProvider.getBean(AccountAssetService.class).method()
以上是“SpringBoot怎么在線程中獲取@Service Bean類”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。