Spring 多线程下注入bean问题

来源:互联网 发布:oracle数据库监控工具 编辑:程序博客网 时间:2024/05/29 06:42

问题

Spring中多线程注入userThreadService注不进去,显示userThreadService为null异常代码如下:

public class UserThreadTask implements Runnable {    @Autowired    private UserThreadService userThreadService;    @Override    public void run() {        AdeUser user = userThreadService.get("0");        System.out.println(user);    }}

解决方案一

把要注入的Service,通过构造传过去,代码如下:

public class UserThreadTask implements Runnable {    private UserThreadService userThreadService;    public UserThreadTask(UserThreadService userThreadService) {        this.userThreadService = userThreadService;    }    @Override    public void run() {        AdeUser user = userThreadService.get("0");        System.out.println(user);    }}
Thread t = new Thread(new UserThreadTask(userThreadService));t.start();

解决方案二

通过ApplicationContext中获取需要使用的Service

import org.springframework.beans.BeansException;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;public class ApplicationContextHolder implements ApplicationContextAware {    private static ApplicationContext context;    @Override    public void setApplicationContext(ApplicationContext context) throws BeansException {        ApplicationContextHolder.context = context;    }    //根据bean name 获取实例    public static Object getBeanByName(String beanName) {        if (beanName == null || context == null) {            return null;        }        return context.getBean(beanName);    }    //只适合一个class只被定义一次的bean(也就是说,根据class不能匹配出多个该class的实例)    public static Object getBeanByType(Class clazz) {        if (clazz == null || context == null) {            return null;        }        return context.getBean(clazz);    }    public static String[] getBeanDefinitionNames() {        return context.getBeanDefinitionNames();    }}

Spring 加载自己定义的ApplicationContextHolder类

<bean class = "cn.com.infcn.applicationcontext.ApplicationContextHolder"></bean>

根据 bean 的名称获取实例

UserService user = (UserService) ApplicationContextHolder.getBeanByName("userService"); 

根据 bean 的Class 获取实例(如果该Class存在多个实例,会报错的)

UserService user = (UserService) ApplicationContextHolder.getBeanByType(UserService.class); 

这种方式,不管是否多线程,还是普通的不收spring管理的类,都可以使用该方法获得spring管理的bean。



作者:jijs
链接:http://www.jianshu.com/p/c8a43d26bc0f
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
原创粉丝点击