How can I get a Spring bean in a servlet filter?
Try:
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:
UsersConnectionRepository bean = WebApplicationContextUtils.
getRequiredWebApplicationContext(filterConfig.getServletContext()).
getBean(UsersConnectionRepository.class);
Also have a look at GenericFilterBean and its subclasses.
Spring have a utility just for this.
In your Filter code, override the init method like this:
public void init(FilterConfig cfg) {
super.init(cfg);
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
}
Then you just @Inject your beans to that filter, same way as any other bean you would inject.
@Inject
private UsersConnectionRepository repository;
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 theFilter
interface.Use
@Configurable
on your filter. I would prefer one of the other two options though. (This option uses aspectj weaving)