本篇文章小编给大家分享一下SpringBoot在线程中获取@Service Bean类代码示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
这个适用于没有Spring配置文件的Springboot项目中,有配置文件的话取bean就方便多了。
下图是用@Service注解声明的一个Mybatis Mapper Bean,平常在Springboot扫描配置下的类直接用
@Autowired注解依赖注入。
现在需要在线程中使用,然而Springboot自然而然只能扫描到自己的东西 ,线程实现的Runnable接口,
我们现在开始解决问题
1、首先创建一个配置类继承ApplicationContextAware,取得ApplicationContext。
利用里面的getBean方法取得你想要的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 staticT getBean(Class aClass){ return context.getBean(aClass); } }
多线程中的调用方式
.method()是bean对象的方法名称
ApplicationContextProvider.getBean(AccountAssetService.class).method()
敢达决战官方正版 安卓版v6.7.9
下载敢达决战 安卓版v6.7.9
下载像素火影骨架佐助 (Perseverance Fire Shadow)手机版v1.16
下载要塞英雄 安卓版v33.20.0-39082670-Android
下载梦想城镇vivo最新版本 安卓版v12.0.1
梦想城镇vivo版是这款卡通风模拟经营类手游的渠道服版本,玩
怦然心动的瞬间 安卓版v1.0
怦然心动的瞬间是一款真人向的恋爱互动游戏,在游戏中玩家将扮演
曼尼汉堡店游戏 安卓版v1.0.3
曼尼汉堡店是一款非常好玩的精品恐怖类型冒险游戏,在这款游戏中
现代总统模拟器去广告版 安卓版v1.0.46
现代总统模拟器是一款休闲养成类游戏,可能对于不少的玩家来说都
现代总统模拟器付费完整版 安卓版v1.0.46
现代总统模拟器高级版在商店是需要付费的,相对于普通版本,高级