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注入

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