我在使用一个简单的弹簧过滤器时遇到了一个奇怪的问题。在init
函数中,我设置了一个变量this.test = "TEST1234"
,但是由于某种原因,当到达doFilter
函数时,该变量再次恢复为空。
我的过滤器:
@Component
public class TestFilter implements Filter {
private String test;
public void init(FilterConfig cfg) {
this.test = "TEST1234";
System.out.println("TEST: " + this.test);
}
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
System.out.println("TEST: " + this.test);
}
public void destroy() {}
}
SecurityConfig:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.addFilterBefore(
new TestFilter(),
AbstractPreAuthenticatedProcessingFilter.class
);
}
}
控制台输出:
init:TEST: TEST1234
doFilter:TEST: null
为什么将此变量恢复为null?我想念什么吗?是垃圾收集吗?
我正在Java 1.8.0_171
上运行我的应用程序
依赖项:
2.1.4.RELEASE
1.0.10.RELEASE
2.2.1.RELEASE
2.5
答案 0 :(得分:0)
通过@dur
的评论解决了该问题。
首先,我删除了@Component
注释,以使我的过滤器不会实例化两次。
过滤器:
public class TestFilter implements Filter {
private String test;
public void init(FilterConfig cfg) {
this.test = "TEST1234";
System.out.println("TEST: " + this.test);
}
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
System.out.println("TEST: " + this.test);
}
public void destroy() {}
}
我还将过滤器实例创建为bean
,而不是直接在newFilter()
函数中调用addFilterBefore()
。
SecurityConfig:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public TestFilter testFilter() {
return new TestFilter();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.addFilterBefore(
testFilter(),
AbstractPreAuthenticatedProcessingFilter.class
);
}
}
控制台输出(现在已预期):
init:TEST: TEST1234
doFilter:TEST: TEST1234