溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

SpringBoot怎么在線程中獲取@Service?Bean類

發布時間:2022-02-27 09:48:10 來源:億速云 閱讀:465 作者:小新 欄目:開發技術

這篇文章主要為大家展示了“SpringBoot怎么在線程中獲取@Service Bean類”,內容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領大家一起研究并學習一下“SpringBoot怎么在線程中獲取@Service Bean類”這篇文章吧。

如何在線程中獲取@Service Bean類

這個適用于沒有Spring配置文件的Springboot項目中,有配置文件的話取bean就方便多了。

下圖是我用@Service注解聲明的一個Mybatis Mapper Bean,平常在Springboot掃描配置下的類直接用

@Autowired注解依賴注入。

SpringBoot怎么在線程中獲取@Service?Bean類

SpringBoot怎么在線程中獲取@Service?Bean類

我現在需要在線程中使用,然而Springboot自然而然只能掃描到自己的東西 ,線程實現的Runnable接口,

我們現在開始解決問題

1、首先創建一個配置類繼承ApplicationContextAware,取得ApplicationContext。

SpringBoot怎么在線程中獲取@Service?Bean類

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

SpringBoot怎么在線程中獲取@Service?Bean類

這樣你就能在線程中得到你要的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類”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女