SpringBoot如何在線程中獲取@Service Bean類
如何在線程中獲取@Service Bean類
這個適用于沒有Spring配置文件的Springboot項目中,有配置文件的話取bean就方便多了。
下圖是我用@Service注解聲明的一個Mybatis Mapper Bean,平常在Springboot掃描配置下的類直接用
@Autowired注解依賴注入。
我現(xiàn)在需要在線程中使用,然而Springboot自然而然只能掃描到自己的東西 ,線程實現(xiàn)的Runnable接口,
我們現(xiàn)在開始解決問題
1、首先創(chuàng)建一個配置類繼承ApplicationContextAware,取得ApplicationContext。
利用里面的getBean方法取得你想要的Bean類。
這樣你就能在線程中得到你要的Bean類了。挺坑的?。?!
多線程中獲取bean對象
注:多線程場景下,使用默認(rèn)的spring自動裝配無法獲取bean對象,此方案可以從context上下文中直接獲取bean。
創(chuàng)建類
實現(xiàn)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); ? ? } }
多線程中的調(diào)用方式
.method()是bean對象的方法名稱
ApplicationContextProvider.getBean(AccountAssetService.class).method()
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Spring Boot應(yīng)用程序同時支持HTTP和HTTPS協(xié)議的實現(xiàn)方法
如今,企業(yè)級應(yīng)用程序的常見場景是同時支持HTTP和HTTPS兩種協(xié)議,這篇文章考慮如何讓Spring Boot應(yīng)用程序同時支持HTTP和HTTPS兩種協(xié)議,需要的朋友可以參考下2019-10-10解決Java導(dǎo)入excel大量數(shù)據(jù)出現(xiàn)內(nèi)存溢出的問題
今天小編就為大家分享一篇解決Java導(dǎo)入excel大量數(shù)據(jù)出現(xiàn)內(nèi)存溢出的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-06-06Java ArrayList的基本概念和作用及動態(tài)數(shù)組的機制與性能
在Java中,ArrayList是一個實現(xiàn)了List接口的動態(tài)數(shù)組,它可以根據(jù)需要自動增加大小,因此可以存儲任意數(shù)量的元素,這篇文章主要介紹了探秘Java ArrayList的基本概念和作用及動態(tài)數(shù)組的機制與性能,需要的朋友可以參考下2023-12-12SpringBoot中Formatter和Converter用法和區(qū)別小結(jié)
本文主要介紹了SpringBoot中Formatter和Converter用法和區(qū)別,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-07-07spring boot 實現(xiàn)阿里云視頻點播功能(刪除視頻)
這篇文章主要介紹了spring boot 實現(xiàn)阿里云視頻點播(刪除視頻功能),本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-12-12