'Properties in application.properties not getting loaded in Filter class
I am trying to read the value from application.properties in one of the util library Filter we write.
My code is as below.
public class AuthorizationFilter extends GenericFilterBean
{
@Value ("${application.identifier}")
private String appId;
...
}
However the value appId is not read from application.properties though it is defined. The issue occurs only with Filter classes.
Any pointers on how to fix this?
Solution 1:[1]
Like @M.Deinum said , If you let spring-boot manage the life cycle of the filter bean, then you will be able use the @Value annotation :
@Component
@Order(1)
public class CustomFilter implements Filter {
@Value ("${application.identifier}")
private String appId;
@Override
public void doFilter
ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
LOG.info(
"Starting for req : {}",
req.getRequestURI());
chain.doFilter(request, response);
LOG.info(
"Anything");
}
// other methods
}
Keep in mind that if you provide your filter this way , you won't have to register it manually and if you want it to work for a particular url by registering it manually remember to remove the @Component annotation so that spring-boot won't take it up automatically.
Solution 2:[2]
Let the spring manage your filter class. You can register in your filter class like below :
@Bean
public FilterRegistrationBean registerFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(this);
registration.addUrlPatterns("/*");
return registration;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | ankita singh |
