[英]Adding filter to servletcontext using ContextStartedEvent in Spring
I want to add a servletFilter
after the Applicationcontext
has been initiailized. 我想在
Applicationcontext
servletFilter
后添加servletFilter。 The reason is that the filter is dependent on userdetailsService bean, which in turn is autowired
to other dependent beans. 原因是过滤器依赖于userdetailsService Bean,后者又
autowired
到其他依赖的Bean。 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. 问题是当我构建应用程序时,可以看到
onApplicationEvent
被调用,但是当我尝试运行应用程序(从浏览器)时,未调用过滤器。
How do I achieve adding the filter to servlet context. 如何实现将过滤器添加到Servlet上下文。
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. 如果我将其添加到实现
webApplicationInitializer
的类的onStartup(ApplicationContext ctx)
方法中,则相同的筛选器,由于Bean尚未初始化,应用程序将抛出未定义的依赖项错误。
@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")
}
}
You can declare your filter as a Bean in a Configuration class: 您可以在Configuration类中将过滤器声明为Bean:
@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. 这样,仅当应用程序上下文初始化时,您的过滤器才会发生。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.