I upgraded Spring Boot dependency in my project and I realized that some classes, such as FilterRegistrationBean, are deprecated.
Do you know how can implement a Filter in Spring Boot 1.4.1?
Bean of Filter
@Bean
public FilterRegistrationBean filterRegistrationBean() {
AuthenticationFilter f = new AuthenticationFilter();
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(f);
registrationBean.addInitParameter("defaultToken", defaultToken);
registrationBean.addInitParameter("secretKey", secretKey);
ArrayList<String> match = new ArrayList<>();
match.add("/users/*");
registrationBean.setUrlPatterns(match);
return registrationBean;
}
My Filter code:
public class AuthenticationFilter implements Filter {
private String defaultToken;
private String secretKey;
private UserSessionTokenRepository userSessionTokenRepository;
private UserManager userManager;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
defaultToken = filterConfig.getInitParameter("defaultToken");
secretKey = filterConfig.getInitParameter("secretKey");
userSessionTokenRepository = WebApplicationContextUtils.getRequiredWebApplicationContext(filterConfig.getServletContext()).getBean(UserSessionTokenRepository.class);
userManager = WebApplicationContextUtils.getRequiredWebApplicationContext(filterConfig.getServletContext()).getBean(UserManager.class);
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
chain.doFilter(request, response);
}
public void addHeaders(HttpServletResponse response) {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Content-Type");
}
public void destroy() {
}
}
FilterRegistrationBean implements ServletContextInitializer. It is used to register a Filter programmatically in a Spring Boot application.
There are three ways to add your filter, Annotate your filter with one of the Spring stereotypes such as @Component. Register a @Bean with Filter type in Spring @Configuration. Register a @Bean with FilterRegistrationBean type in Spring @Configuration.
The FilterRegistrationBean is, as the name implies, a bean used to provide configuration to register Filter instances. It can be used to provide things like URL mappings etc.
It has been moved to another package: http://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/web/servlet/FilterRegistrationBean.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With