SpringBoot thread can not inject Bean by @Autowired

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/bj_chengrong/article/details/88828462
package com.wis.mes.context;

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

/**
 * @Author CHENEY
 * @Date 2019/03/26
 * @Version 1.0
 * @Last Modified By : CHENEY
 * @Last Modified Time : 2019/03/26
 * @Description :  bean对象的工具类 (ApplicationContextProvider Service)
 * @function:针对多线程无法使用Autowired注入Bean设计
 * @Type implements class
 * Copyright (c) 2019 WIS Software Co.*
 */
@Component
public class ApplicationContextProvider implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.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);
    }

    / ** 
     * Get Bean by class 
     * 
     * @param clazz 
     * @param <T> 
     * @return 
     * / 
    public static <T> T the getBean (Class <T> clazz) { 
        return getApplicationContext () the getBean (clazz);. 
    } 

    / ** 
     * returns specified by name, and Bean clazz 
     * 
     * @param name 
     * @param clazz 
     * @param <T> 
     * @return 
     * / 
    public static <T> T the getBean (String name, Class <T> clazz) { 
        return getApplicationContext().getBean(name, clazz);
    } 
}

 

-------------------------------------------------- ------ usage:

DataCoreService dataCoreService = ApplicationContextProvider.getBean(DataCoreService.class);

 

Guess you like

Origin blog.csdn.net/bj_chengrong/article/details/88828462