SpringBoot在线程中取得@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类了。挺坑的!!!