如何在 servlet 过滤器中获取 Spring bean? [英] How can I get a Spring bean in a servlet filter?

查看:53
本文介绍了如何在 servlet 过滤器中获取 Spring bean?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have defined a javax.servlet.Filter and I have Java class with Spring annotations.

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

@Configuration
public class SocialConfig {

    // ...

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

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

I want to get the bean UsersConnectionRepository in my Filter, so I tried the following:

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

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

But it always returns null. How can I get a Spring bean in a Filter?

推荐答案

尝试:

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

其中 usersConnectionRepository 是应用程序上下文中 bean 的名称/ID.甚至更好:

Where usersConnectionRepository is a name/id of your bean in the application context. Or even better:

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

也看看 GenericFilterBean 及其子类.

这篇关于如何在 servlet 过滤器中获取 Spring bean?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆