问题:Java web 过滤器使用@Value属性为null
现象:
application.yaml配置文件如下:
app.system.id=20191010
app.service.secretkey=123456
过滤器配置
@WebFilter(urlPatterns = "/api/*", filterName = "SSOConfig")
public class SSOConfig implements Filter {
@Value("${app.system.id}")
private String systemId;
@Value("${app.service.secretkey}")
private String secretKey;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
//本地开发阶段是可以获取到值得
System.out.println(systemId);
System.out.println(secretKey);
filterChain.doFilter(request, response);
}
@Override
public void destroy() {
}
}
分析:Javaweb项目启动时,加载顺序导致的。
在web.xml中各个元素的执行顺序:
context-param–>listener–>filter–>servlet
而拦截器是在Spring MVC中配置的,如果从整个项目中看,一个servlet请求的执行过程就变成了这样:
context-param–>listener–>filter–>servlet–>interceptor(指的是拦截器)->spring
因此注入的值为null,使用@Autowired注入bean的话,也是注入不了,值也为null。
思路:
将要注入的数据从filter分离,当服务启动完毕后,过滤方法中再调用。
解决:
可以使用static变量,然后再为变量赋值的方法实现。
@Component
public class SSOUtil {
public static String systemId;
public static String secretKey;
@Value("${app.system.id}")
public void setSystemId(String systemId) {
SSOUtil.systemId=systemId;
}
@Value("${app.service.secretkey}")
public void setSecretKey(String secretKey) {
SSOUtil.secretKey=secretKey;
}
public static String getApp() {
return systemId+":"+secretKey;
}
}
@WebFilter(urlPatterns = "/api/*", filterName = "SSOConfig")
public class SSOConfig implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
System.out.println(SSOUtil.getApp());
filterChain.doFilter(request, response);
}
@Override
public void destroy() {
}
}