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

新手上路,请多包涵

我已经定义了一个 javax.servlet.Filter 并且我有带有 Spring 注释的 Java 类。

 import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;

@Configuration
public class SocialConfig {

    // ...

    @Bean
    public UsersConnectionRepository usersConnectionRepository() {
        // ...
    }
}

我想在我的 --- 中获取 bean UsersConnectionRepository Filter ,所以我尝试了以下操作:

 public void init(FilterConfig filterConfig) throws ServletException {
    UsersConnectionRepository bean = (UsersConnectionRepository) filterConfig.getServletContext().getAttribute("#{connectionFactoryLocator}");
}

但它总是返回 null 。如何在 Filter 中获取 Spring bean?

原文由 IturPablo 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 614
2 个回答

尝试:

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

其中 usersConnectionRepository 是您的 bean 在应用程序上下文中的名称/id。或者更好:

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

还可以查看 GenericFilterBean 及其子类。

原文由 Tomasz Nurkiewicz 发布,翻译遵循 CC BY-SA 3.0 许可协议

有以下三种方式:

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

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

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

原文由 Bozho 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题