springboot 靜態方法獲取Bean


實現ApplicationContextAware

ApplicationContextAware 通過它Spring容器會自動把上下文環境對象調用ApplicationContextAware接口中的setApplicationContext方法。

我們在ApplicationContextAware的實現類中,就可以通過這個上下文環境對象得到Spring容器中的Bean。

看到—Aware就知道是干什么的了,就是屬性注入的,但是這個ApplicationContextAware的不同地方在於,實現了這個接口的bean,當spring容器初始化的時候,會自動的將ApplicationContext注入進來:


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

@Component
public class SpringContextHolder implements ApplicationContextAware {

    private static ApplicationContext applicationContext = null;

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

    public static <T> T getBean(Class<T> type) {
        assertContextInjected();
        return applicationContext.getBean(type);
    }

    public static void assertContextInjected() {
        if (applicationContext == null) {
            throw new RuntimeException("applicationContext未注入");
        }
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM