Adding filter to servletcontext using ContextStartedEvent in Spring

1.2k Views Asked by At

I want to add a servletFilter after the Applicationcontext has been initiailized. The reason is that the filter is dependent on userdetailsService bean, which in turn is autowired to other dependent beans. Issue is when I build the application I can see the onApplicationEvent getting called but when i try to run the application(from browser) the filter is not getting called.

How do I achieve adding the filter to servlet context.

The same filters if i add it onStartup(ApplicationContext ctx) method of class implementing webApplicationInitializer, application is throwing unstatisfied dependencies error because the beans have not been initialized yet.

@Component
public class AppContextStartedListener implements ApplicationListener<ContextStartedEvent> {

@Autowired
private MyAppFilter myAppFilter;

    @Override
    public void onApplicationEvent(ContextStartedEvent event) {
        System.out.println("Context started"); // this never happens
        ServletContext = event.getServletContext // demo code to fetch Servlet 
                         Context
        FilterRegistere.Dynamic appFilter = ServletContext.addFilter("",myAppFilter)
appFilter.setInitParameter("init","initit")

    }
}
1

There are 1 best solutions below

2
Z.yassine On

You can declare your filter as a Bean in a Configuration class:

@Configuration
public class MyConfig {

  @Bean
  public MyAppFilter myAppFilter() {
     return new MyAppFilter();
  }
}

This way, your filter will take place only when the app context is initialized.