0

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")

    }
}
cjava
  • 656
  • 1
  • 8
  • 22

1 Answers1

0

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.

Z.yassine
  • 186
  • 1
  • 2
  • 10
  • actually i have multiple filter and i need to maintain the orders too. Also i need the init parameters set to filter – cjava Aug 04 '18 at 16:50
  • 1
    add @Order Spring annotation which will maintain the order for you or you can do it this way : see https://stackoverflow.com/questions/25957879/filter-order-in-spring-boot – Z.yassine Aug 04 '18 at 16:55