I'm pretty new to Spring and I want to migrate some old Spring 4 project to Spring Boot 2.X. I'm facing the issue with the filters initialization. In the current approach I have something like this:
public class MyWebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() { return new Class[]{ Configuration1.class, Configuration2.class, Configuration3.class};}
@Override
protected Class<?>[] getServletConfigClasses() { return null; }
@Override
@NonNull
protected String[] getServletMappings() { return new String[]{"/"}; }
@Override
public void onStartup(final ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
//MY FILTERS
FilterRegistration.Dynamic corsFilter = servletContext.addFilter("corsFilter", DelegatingFilterProxy.class);
corsFilter.addMappingForUrlPatterns(null, false, "/*");
corsFilter.setAsyncSupported(true);
//.... more filters there
}
As I understand it was done like this because of bean initialization occurs later than onStartup method (not sure though, correct me if I'm wrong).
I copy-pasted filters initialization logic to onStartup() of ServletContextInitializer class when migrating the app to spring boot. Unfortunately, I'm facing such issue right now when trying to access dispatcher and forward request further:
public final class MyFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//some logic
String servlet = filterConfig.getInitParameter("servlet");
RequestDispatcher rd = servletContext.getNamedDispatcher(servlet); // null pointer here :(
rd.forward(new RESTPathServletRequest((HttpServletRequest) request), response);
}
My questions are as follow:
- What's the proper approach of using filters in spring boot?
- Why
onStartupinServletContextInitializerhave different flow thenonStartupinAbstractAnnotationConfigDispatcherServletInitializer(looks like beans are initialized early on) - Is there any way to simulate
AbstractAnnotationConfigDispatcherServletInitializerlogic usingServletContextInitializeras my local runner.