温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

SpringBoot怎么在线程中获取@Service Bean类

发布时间:2022-02-27 09:48:10 来源:亿速云 阅读:401 作者:小新 栏目:开发技术

这篇文章主要为大家展示了“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