SpringBoot项目多线程中bean无法注入问题处理

一、定义bean获取工具类

/**
 * spring 上下文辅助类
 * @author 
 */
public class SpringContextUtil {

    private static ApplicationContext applicationContext;

    private SpringContextUtil() {
        //spring 上下文辅助类
    }

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

    /**
     * 设置上下文
     * @param applicationContext
     */
    public static void setApplicationContext(ApplicationContext applicationContext) {
        SpringContextUtil.applicationContext = applicationContext;
    }

    /**
     * 通过名字获取上下文中的bean
     * @param name
     * @return
     */
    public static Object getBean(String name){
        return applicationContext.getBean(name);
    }

    /**
     * 通过类型获取上下文中的bean
     * @param requiredType
     * @return
     */
    public static Object getBean(Class requiredType){
        return applicationContext.getBean(requiredType);
    }

}

2.在springboot启动类中设置ApplicationContext 

@SpringBootApplication
public class WebApplication {

  /**
   * main
   * @param args args
   */
  public static void main(String[] args) {
  
    ApplicationContext app = SpringApplication.run(WebApplication.class, args);
    // 设置上下文
    SpringContextUtil.setApplicationContext(app);
  }


}

3.线程中获取bean

public class LogJob implements Runnable {

    /**
     * 日志
     */
    private static final transient Logger LOGGER = LoggerFactory.getLogger(LogJob.class);

    private LogHandler logHandler;

    private int retentionDays = 30;

    public LogJob(){
        ApplicationContext applicationContext = SpringContextUtil.getApplicationContext();
        logHandler = applicationContext.getBean(LogHandler.class);
        //获取配置中信息
        String retentionDaysStr = applicationContext.getEnvironment().getProperty("log.retentionDays");
        if (StringUtils.isNotEmpty(retentionDaysStr)) {
            retentionDays = Integer.parseInt(retentionDaysStr);
        }
    }


    @Override
    public void run() {
        LOGGER.info(">>>>>>>>>>>>>>>>>>当前线程名称{}",Thread.currentThread().getName());
        try {
            logHandler.processLog(retentionDays);
        } catch (IOException e) {
            LOGGER.error(">>>>>>>>>>>>>>>>>>处理日志异常", e);
        }

    }

}

 

你可能感兴趣的:(Java)