您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何在servlet过滤器中获取Spring bean?

如何在servlet过滤器中获取Spring bean?

尝试:

UsersConnectionRepository bean = 
  (UsersConnectionRepository)WebApplicationContextUtils.
    getrequiredWebApplicationContext(filterConfig.getServletContext()).
    getBean("usersConnectionRepository");

usersConnectionRepository你的bean在应用程序上下文中的名称/标识在哪里。甚至更好:

UsersConnectionRepository bean = WebApplicationContextUtils.
  getrequiredWebApplicationContext(filterConfig.getServletContext()).
  getBean(UsersConnectionRepository.class);

还可以看看GenericFilterBean及其子类。

有三种方法

public void init(FilterConfig cfg) { 
    ApplicationContext ctx = WebApplicationContextUtils
      .getrequiredWebApplicationContext(cfg.getServletContext());
    this.bean = ctx.getBean(YourBeanType.class);
}

使用DelegatingFilterProxy-映射该过滤器,然后将过滤器声明为bean。然后,委托代理将调用实现该Filter接口的所有bean 。

@Configurable在你的过滤器上使用。我更喜欢其他两个选项之一。(此选项使用aspectj编织)

Jave 2022/1/1 18:22:38 有310人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶