线程中无法自动注入bean

原创
2018/07/13 15:44
阅读数 1.2K

编写一个获取上下文所有的bean的工具类

public class SpringContextUtil implements ApplicationContextAware{

    // Spring应用上下文环境
    private static ApplicationContext applicationContext;
    /**
     * 实现ApplicationContextAware接口的回调方法,设置上下文环境
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
    /**
     * 获取对象 这里重写了bean方法,起主要作用
     * example: getBean("userService")//注意: 类名首字母一定要小写!
     */
    public static Object getBean(String beanId) throws BeansException {
        return applicationContext.getBean(beanId);
    }

}

线程类里面调用

public class ProductThread implements Runnable{

    private final ProductService productService = (ProductService) SpringContextUtil.getBean("productService");

    private final IntegralOrderService integralOrderService = (IntegralOrderService) SpringContextUtil.getBean("integralOrderService");


    private Integer type;
    private Integer productId;
    private Integer userId;

    public ProductThread(Integer type,Integer productId,Integer userId){
        this.type = type;
        this.productId = productId;
        this.userId = userId;
    }
    @Override
    public void run() {
        //添加
        System.out.println("进入线程!");
        if(type==1){
            this.placeAnOrder(productId,userId);
        }       
    }

    public void placeAnOrder(Integer productId,Integer userId){
       *******************
    }

}

这样就可以了,但是有一点,如果线程写成内部类,就不用写工具类。

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部