问题描述
尝试:
UsersConnectionRepository bean =
(UsersConnectionRepository)WebApplicationContextUtils.
getrequiredWebApplicationContext(filterConfig.getServletContext()).
getBean("usersConnectionRepository");
usersConnectionRepository
你的bean在应用程序上下文中的名称/标识在哪里。甚至更好:
UsersConnectionRepository bean = WebApplicationContextUtils.
getrequiredWebApplicationContext(filterConfig.getServletContext()).
getBean(UsersConnectionRepository.class);
还可以看看GenericFilterBean及其子类。
有三种方法:
- 用途
WebApplicationContextUtils
:
public void init(FilterConfig cfg) {
ApplicationContext ctx = WebApplicationContextUtils
.getrequiredWebApplicationContext(cfg.getServletContext());
this.bean = ctx.getBean(YourBeanType.class);
}
-
使用
DelegatingFilterProxy
-映射该过滤器,然后将过滤器声明为bean。然后,委托代理将调用实现该Filter
接口的所有bean 。 -
@Configurable
在你的过滤器上使用。我更喜欢其他两个选项之一。(此选项使用aspectj编织)
解决方法
我定义了一个,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
。我怎样才能得到一个Spring beanFilter
?