Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a Spring bean in a servlet filter?

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?

like image 672
IturPablo Avatar asked Oct 24 '11 21:10

IturPablo


People also ask

How do you use Spring Filters?

There are three ways to add your filter, Annotate your filter with one of the Spring stereotypes such as @Component. Register a @Bean with Filter type in Spring @Configuration. Register a @Bean with FilterRegistrationBean type in Spring @Configuration.

How does filter work in servlet?

A filter is an object that is invoked at the preprocessing and postprocessing of a request. It is mainly used to perform filtering tasks such as conversion, logging, compression, encryption and decryption, input validation etc. The servlet filter is pluggable, i.e. its entry is defined in the web.


1 Answers

There are three ways:

  1. Use WebApplicationContextUtils:

    public void init(FilterConfig cfg) {      ApplicationContext ctx = WebApplicationContextUtils       .getRequiredWebApplicationContext(cfg.getServletContext());     this.bean = ctx.getBean(YourBeanType.class); } 
  2. 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.

  3. Use @Configurable on your filter. I would prefer one of the other two options though. (This option uses aspectj weaving)

like image 111
Bozho Avatar answered Oct 12 '22 10:10

Bozho