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() {
// ...
}
}
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}");
}
But it always returns null
. How can I get a Spring bean in a Filter
?
There are three ways:
Use WebApplicationContextUtils
:
public void init(FilterConfig cfg) {
ApplicationContext ctx = WebApplicationContextUtils
.getRequiredWebApplicationContext(cfg.getServletContext());
this.bean = ctx.getBean(YourBeanType.class);
}
Using the DelegatingFilterProxy
- you map that filter, and declare your filter as bean. The delegating proxy will then invoke all beans that implement the Filter
interface.
Use @Configurable
on your filter. I would prefer one of the other two options though. (This option uses aspectj weaving)