多线程注入spring bean

2,424 阅读1分钟

多线程注入spring bean的时候使用@autowried时会导致 注入的bean对象为null 

解决方案 

使用applicationcontext手动注入bean

注:工具类也需要被spring 托管可使用注解也可以在xml中手动配置

工具类:

package com.right.amanbo.b2c.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author 明丶
 * @date 2019/11/25 14:11
 */
@Component
public class SpringContextUtil implements ApplicationContextAware  {

    private static ApplicationContext applicationContext = null;
    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        applicationContext = context;
    }
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 根据name获取bean
     * @param beanName
     * @param <T>
     * @return
     */
    public static <T> T getBeanByName(String beanName) {
        if (applicationContext == null){
            return null;
        }
        return (T)applicationContext.getBean(beanName);
    }

    /**
     * 根据id获取bean
     * @param id
     * @param <T>
     * @return
     */
    public static <T> T getBeanById(String id) {
        if (applicationContext == null){
            return null;
        }
        return (T) applicationContext.getBean(id);
    }

    /**
     * 根据class获取bean
     * @param c
     * @param <T>
     * @return
     */
    public static <T> T getBeanByClass(Class c) {
        if (applicationContext == null){
            return null;
        }
        return (T)applicationContext.getBean(c);
    }

}

调用:

/**
 * @author 明丶
 */
@SuppressWarnings("unchecked")
public class SendMsgThread implements Runnable {
    private SysNoticeService sysNoticeService;
    private RedPacketService redPacketService;
    private Object list;
    private Template template;
    private Integer type;
    private RedPacketDTO red;
    public SendMsgThread(Object list, Template template, int type, RedPacketDTO red) {
        this.redPacketService = SpringContextUtil.getBeanByClass(RedPacketService.class);
        this.sysNoticeService = SpringContextUtil.getBeanByClass(SysNoticeService.class);
        this.list = list;
        this.template = template;
        this.type = type;
        this.red = red;
    }