SpringBoot-多线程处理任务-无法Autowired注入bean问题解决

43次阅读

共计 1697 个字符,预计需要花费 5 分钟才能阅读完成。

在多线程处理问题时,无法通过 @Autowired 注入 bean,报空指针异常,

在线程中为了线程安全,是防注入的,如果要用到这个类,只能从 bean 工厂里拿个实例。

解决方法如下:

1. 创建一个工具类代码:

package com.hqgd.pms.common;

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

/**
 * @Description: 获取 bean 对象的工具类
 * @Author: yaorong
 * @CreateDate: 2018/12/10
 */

@Component
public class SpringContextUtil implements ApplicationContextAware {
    /**
     * 上下文对象实例
     */
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {SpringContextUtil.applicationContext = applicationContext;}

    /**
     * 获取 applicationContext
     *
     * @return
     */
    public static ApplicationContext getApplicationContext() {return applicationContext;}

    /**
     * 通过 name 获取 Bean.
     *
     * @param name
     * @return
     */
    public static Object getBean(String name) {return getApplicationContext().getBean(name);
    }

    /**
     * 通过 class 获取 Bean.
     *
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> clazz) {return getApplicationContext().getBean(clazz);
    }

    /**
     * 通过 name, 以及 Clazz 返回指定的 Bean
     *
     * @param name
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(String name, Class<T> clazz) {return getApplicationContext().getBean(name, clazz);
    }
}

2. 使用方法

@Slf4j
@Service
public class SerialPortService {
    public static SerialPort mSerialport = null;
//    private SimpMessagingTemplate simpMessage;
    private DataAcquisitionService das;
    private SystemService systemService;
    private SysParamMapper sysParamMapper;

    public SerialPortService() {this.das = SpringContextUtil.getBean(DataAcquisitionService.class);
        this.systemService = SpringContextUtil.getBean(SystemService.class);
        this.sysParamMapper = SpringContextUtil.getBean(SysParamMapper.class);
    }

}

正文完
 0