Spring 多线程下注入bean问题

作者: jijs | 来源:发表于2017-10-14 23:25 被阅读536次

问题

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。

想了解更多精彩内容请关注我的公众号

相关文章

网友评论

    本文标题:Spring 多线程下注入bean问题

    本文链接:https://www.haomeiwen.com/subject/xfxzyxtx.html