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

查看:367
本文介绍了如何在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的名称/标识.甚至更好:

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);

也请参阅 查看全文

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