SpringBoot多线程下的bean管理——SpringBoot中多线程用Autowired或@Resource注入bean失败报NullPointException

在项目开发过程中,有碰到多线程下用@Autowired或@Resource注入失败,报NullPointException的情况,这就要从Spring对Bean的管理来说明了,这是是因为创建的多线程无法获取到Spring容器中的bean。这体现了熟悉框架原理和底层实现的重要性。

可以有以下解决方法:

   1、通过内部类来实现

@Component
public class ThreadBean {
    @Autowired
    MyService myService;
    public void execute(){
        ExecutorService executorService= Executors.newCachedThreadPool();
        executorService.execute(new MyTread());
    }
    private class MyTread implements Runnable{

        @Override
        public void run() {
            dosomeThing();
        }
    }
    public void dosomeThing(){
        System.out.println("do something"+myService.getTime());
    }
}
  将该类作为Bean组件调用,实现多线程
@Component
public class QuartzTask {
    @Autowired
    ThreadBean threadBean;
    @Scheduled(cron = "0/3 * * * * ?  ")
    public void scheduled(){
        threadBean.execute();
    }
}

  2、编码通过Spring的上下文对象获取bean   

public class ApplicationContextProvider implements ApplicationContextAware {

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


    private static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    
    public static Object getBean(String beanName) {
        if (null==beanName||"".equals(beanName)) {
            return "bean name is required!";
        }
        return getApplicationContext()==null?null:getApplicationContext().getBean(beanName);
    }

    
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }
}
 

   3、通过构造函数来获取

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值