spring boot 配置 獲取spring 上下文用來自行獲取bean操作

第一步:實現 ApplicationContextAware接口

第二步:給類加上註解 @Component 讓spring識別並且注入

第三步:定義好靜態的 ApplicationContext ,在ApplicationContextAware實現的   setApplicationContext賦值過去;

後面就是自己根據自己的需求定義獲取bean的接口

如:

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

/**
 * Created by Lee on 2018/5/7.
 */
@Component
public class DemoApplicationContextHelper implements ApplicationContextAware {
    private static ApplicationContext context;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        System.out.println("我已經注入啦");
            context=applicationContext;
    }
    public static <T> T getBean(Class<T> tClass){
        if(null==context){
            return null;
        }
        return context.getBean(tClass);
    }
}

注:如果項目啓動後ApplicationContext爲空的話,可能是項目配置了全局spring bean的懶加載功能,這時候就需要在類上加個註解: @Lazy(value=false)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章