这篇文章主要介绍了SpringBoot如何在线程中获取@ServiceBean类,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
如何在线程中获取@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 static <T> T getBean(Class<T> aClass){
return context.getBean(aClass);
}
}
多线程中的调用方式
.method()是bean对象的方法名称
ApplicationContextProvider.getBean(AccountAssetService.class).method()
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程学习网。
本文标题为:SpringBoot如何在线程中获取@Service Bean类


基础教程推荐
- JVM分析之类加载机制详解 2023-04-06
- 工厂方法在Spring框架中的运用 2023-06-23
- 用java实现扫雷游戏 2022-12-06
- Java使用EasyExcel进行单元格合并的问题详解 2023-01-18
- Java File类的概述及常用方法使用详解 2023-05-18
- 全局记录Feign的请求和响应日志方式 2023-01-09
- Project Reactor源码解析publishOn使用示例 2023-04-12
- SpringBoot配置文件中密码属性加密的实现 2023-03-11
- Java去掉小数点后面无效0的方案与建议 2023-02-18
- 一文了解Java 线程池的正确使用姿势 2023-06-17