spring boot 獲取ApplicationContext

使用springboot開發(fā)時,有一個需求是在過濾器filter中判斷用戶登錄的信息,于是我寫了一個UserService,并且在過濾器中實現(xiàn)自動裝配(@Autowired)。使用springboot自帶的服務器啟動時沒有問題,但是使用外部的Tomcat啟動時就不能實現(xiàn)自動裝配了,報NullPointerException錯誤。搞了半天不知道什么原因,我就想到用ApplicationContext的方式來獲取UserService,具體如下:

  1. 新建SpringContext類(這個類要和springboot啟動類放一起):
@Component
@Lazy(false)
public class SpringContext implements ApplicationContextAware {
    private static ApplicationContext applicationContext;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }
    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }
}
  1. 使用:
//通過class獲得bean
UserService userService= SpringContext.getBean(UserService.class);
//通過name獲得bean
UserService userService= SpringContext.getBean("userService");
//通過name,以及Clazz返回指定的Bean
UserService userService= SpringContext.getBean("userService",UserService.class);
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容