【问题标题】:Adding filter to servletcontext using ContextStartedEvent in Spring在 Spring 中使用 ContextStartedEvent 将过滤器添加到 servletcontext
【发布时间】:2019-01-12 04:52:25
【问题描述】:

我想在Applicationcontext 初始化后添加一个servletFilter。原因是过滤器依赖于 userdetailsS​​ervice bean,而后者又是 autowired 到其他依赖的 bean。问题是当我构建应用程序时,我可以看到 onApplicationEvent 被调用,但是当我尝试运行应用程序(从浏览器)时,过滤器没有被调用。

如何实现将过滤器添加到 servlet 上下文。

如果我添加相同的过滤器onStartup(ApplicationContext ctx) 实现webApplicationInitializer 的类的方法,应用程序将抛出未统计的依赖关系错误,因为尚未初始化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")

    }
}

【问题讨论】:

    标签: java spring spring-mvc servlet-filters spring-filter


    【解决方案1】:

    您可以在配置类中将过滤器声明为 Bean:

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

    这样,您的过滤器将仅在应用上下文初始化时发生。

    【讨论】:

    • 实际上我有多个过滤器,我也需要维护订单。我还需要将初始化参数设置为过滤
    • 添加@Order Spring 注释,它将为您维护订单,或者您可以这样做:请参阅stackoverflow.com/questions/25957879/…
    猜你喜欢
    • 2016-02-11
    • 2016-02-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-24
    • 1970-01-01
    • 1970-01-01
    • 2012-01-22
    • 1970-01-01
    相关资源
    最近更新 更多