springboot中使用filter時注入bean爲null的解決辦法

過濾器是servlet規範中定義的,並不歸spring容器管理,也無法直接注入spring中的bean(會報錯)

初始化時通過spring上下文獲取,進行bean的初始化

@Override
public void init(FilterConfig filterConfig) throws ServletException {
    ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(filterConfig.getServletContext());
    RedisTemplate demoBean = (RedisTemplate)context.getBean("redisTemplate");
    System.out.println(demoBean);
 }

參考資料

1、如何在SpringBoot的 過濾器之中注入Bean對象

2、過濾器使用與bean注入

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