在多线程类中,Spring注入对象为null问题处理

本文探讨了在Spring框架中进行多线程开发时,如何解决Bean注入问题。提供了两种解决方案:一是将线程类注册为Spring Bean;二是通过自定义工具类手动获取Bean实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在开发中经常会使用spring的@Autowired或@Resource来实现对象的自动注入,但是在最近的开发中在多线程中用Spring来自动注入时总是注入不进去,对象显示为null。

后来了解到 spring bean 出于线程安全考虑,不得注入bean至线程类(Runnable),如果线程中想使用spring实例,有两种方法:

1、将ThreadTest类也作为一个bean注入到spring容器中:


public class SpringMultiThreadTest{    
    @Autowired  
    private ThreadTest threadTest;  //将线程类作为对象注入  
    @Test    
    public void testSpringBean(){    
        for (int i=0; i<10000000; i++){    
            new Thread(threadTest).start();    
        }    
        try {    
            Thread.sleep(1000);    
        }catch (InterruptedException e){    
            e.printStackTrace();    
        }    
    }    
}


2、使用Spring手动获得ServiceBean:

   (1)先写一个手动获得Spring bean的工具类


public class SpringBeanUtil implements ApplicationContextAware{    
        
    private static ApplicationContext applicationContext = null;    
    
    @Override    
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {    
        SpringBeanUtil.applicationContext = applicationContext;    
    }    
    
    public static Object getBeanByName(String beanName) {    
        if (applicationContext == null){    
            return null;    
        }    
        return applicationContext.getBean(beanName);    
    }    
    
    public static <T> T getBean(Class<T> type) {    
        return applicationContext.getBean(type);    
    }    
    
}



   (2)ThreadTest类中不自动获取,而是手动获取

public class ThreadTest implements Runnable{    
    private ServiceBean serviceBean;    
    private static AtomicInteger count = new AtomicInteger(0);    
    public ThreadRunner(){    
        this.serviceBean = (ServiceBean)SpringBeanUtil.getBeanByName("serviceBean");    
    }    
    @Override    
    public void run(){    
        if (serviceBean ==null){    
            return;    
        }    
        serviceBean.log();    
        count.addAndGet(1);    
        System.out.println("当前线程为:" + Thread.currentThread().getName() + "count:" + count);    
    }    
    
    public ServiceBean getServiceBean() {    
        return serviceBean;    
    }    
    
    public void setServiceBean(ServiceBean serviceBean) {    
        this.serviceBean = serviceBean;    
    }    
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值