I'm having a weird problem with a simple spring filter I'm using. In the init
function I'm setting a variable this.test = "TEST1234"
but for some reason when reaching then doFilter
function this variable is reverted to null again.
My filter:
@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
);
}
}
Console output:
init: TEST: TEST1234
doFilter: TEST: null
Why is this variable reverted to null? Am I missing something? Is it garbage collected?
I'm running my application on Java 1.8.0_171
Dependencies:
2.1.4.RELEASE
1.0.10.RELEASE
2.2.1.RELEASE
2.5
Solved it thanks to the comment from @dur
.
First I removed the @Component
annotation so my filter doesn't get instantiated twice.
Filter:
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() {}
}
Also I have created the filter instance as a bean
instead of calling newFilter()
directly in the addFilterBefore()
function.
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
);
}
}
Console output (now as expected):
init: TEST: TEST1234
doFilter: TEST: TEST1234