I have defined a javax.servlet.Filter
and I have Java class with Spring annotations.
JavaScript
x
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:
JavaScript
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
?
Advertisement
Answer
Try:
JavaScript
UsersConnectionRepository bean =
(UsersConnectionRepository)WebApplicationContextUtils.
getRequiredWebApplicationContext(filterConfig.getServletContext()).
getBean("usersConnectionRepository");
Where usersConnectionRepository
is a name/id of your bean in the application context. Or even better:
JavaScript
UsersConnectionRepository bean = WebApplicationContextUtils.
getRequiredWebApplicationContext(filterConfig.getServletContext()).
getBean(UsersConnectionRepository.class);
Also have a look at GenericFilterBean and its subclasses.