在Filter中不能注入bean的问题及解决
目录
- Filter中不能注入bean的问题
- Filter中注入bean 无效为null
- 问题原因
- 解决办法
Filter中不能注入bean的问题
WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext()); ApiController apiController = (ApiController) webApplicationContext.getBean("apiController");
Filter中注入bean 无效为null
问题原因
Web应用的启动顺序是:
Lisenter->Fliter->Servlet, 应用程序上下文, 初始化 Fliter的时候,还没有初始化Servlert,所有没有进入DispacterServlet的初始化,故在Fliter中使用注解注入bean为空;
解决办法
添加初始化bean配置,手动创建对象new
代码如下:
package com.test.config; import com.alibaba.druid.support.http.StatViewServlet; import com.test.service.RequestFilter; import javax.servlet.Filter; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.filter.DelegatingFilterProxy; /** * @author lucasliang * @date 08/11/2018 5:56 afternoon filter load before dispathServlet ,so load RequestFilter as a * bean,new a RequestFilter */ @Configuration public class FilterConfig { /* *@param: [] *@return javax.servlet.Filter *@author lucasliang *@date 20/12/2018 *@Description filter */ @Bean public Filter uploadFilter() { return new RequestFilter(); } /* *@param: [] *@return org.springframework.boot.web.servlet.FilterRegistrationBean *@author lucasliang *@date 20/12/2018 *@Description filter */ @Bean @SuppressWarnings("unchecked") public FilterRegistrationBean testFilterRegistration() { FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(new DelegatingFilterProxy("uploadFilter")); registration.addUrlPatterns("/*"); registration.addInitParameter("paramName", "paramValue"); registration.setName("testFilter"); registration.setOrder(1); registration.setEnabled(false); return registration; } }
其中RequestFilter是手动创建的bean,实现了Filter接口
package com.test.service; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; public class RequestFilter implements Filter { private Logger logger = LoggerFactory.getLogger(Filter.class); @Value(value = "${encodeRules}") private String encodeRules; }
此时,在RequestFilter中使用@Value注解,就可以取到值了,注入bean也相同,会取到对应的bean。
至此问题解决!
总结:不管做什么事,首先要搞清楚他的原理,要不,解决了问题下次遇到了还是不会!
以上为个人经验,希望能给大家一个参考,也希望大家多多支持自由互联。
【本文由http://www.nextecloud.cn/hk.html首发,转载请保留出处,谢谢】