2

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:

  1. What's the proper approach of using filters in spring boot?
  2. Why onStartup in ServletContextInitializer have different flow then onStartup in AbstractAnnotationConfigDispatcherServletInitializer (looks like beans are initialized early on)
  3. Is there any way to simulate AbstractAnnotationConfigDispatcherServletInitializer logic using ServletContextInitializer as my local runner.
BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
Kacper Opyrchał
  • 319
  • 2
  • 10
  • [Start from here](https://stackoverflow.com/questions/19825946/how-to-add-a-filter-class-in-spring-boot) – emotionlessbananas Nov 27 '19 at 08:27
  • 1
    Declare the filters as beans using `@Bean` methods, if you need further customizations add an `FilterRegistrationBean` as well. 2. Because Spring Boot controls the container as well it needs early init, 3. just declare them as beans, don't try to outsmart the framework. – M. Deinum Nov 27 '19 at 08:27

0 Answers0