Spring项目中多线程通过@Autowired注入bean对象一直为null问题

  • 问题描述

Spring项目中创建的线程通过@Autowired自动注入bean对象,但是bean一直为null,并引起NullPointerException异常。

  • 问题原因

创建的线程不在Spring容器中,无法获得Spring容器中的bean对象。

  • 解决办法

通过java代码手动获取。

  • 代码示例

(1)继承ApplicationContextAware接口,复写setApplicationContext方法,用于获取应用上下文,并添加@Component注解用于加载。

@Component
public class BeanContext implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        BeanContext.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

}

(2)创建的线程中,通过代码手动获取,如获取OperateHandler对象。

public class SendWorker implements Runnable {

    private OperateHandler handler;

    public SendWorker() {
        this.handler = BeanContext.getApplicationContext().getBean(OperateHandler.class);
    }

    @Override
    public void run() {
        //...
    }
}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值