Question

I have a servlet filter declared like so:

@Component
public class BlahBlahFilter extends OncePerRequestFilter implements Filter {

with a property declared like so:

@Autowired  
@Qualifier("appProperties") 
AppProperties properties;

I have the same Autowired declaration in many of my components in the app and no problems with them - but they are all controllers, services and other misc stuff with @Component tag

But just this filter class is being ignored, and I cannot figure out how to get Spring to inject the property into it.

I noticed in my debug log file this was written next to this class name during component scan:

"Ignored because not a concrete top-level class" 

Huh? Yes it is a concrete class, it is not abstract nor is it an interface. Seems very fishy....

What can I do?

I saw some other topics on this and they were absolutely no help. Neither of them have an accepted answer and none of the posts helped my situation either.

Other relevant code snippets which may help:

web.xml:

  <filter>
  <filter-name>blahBlahFilter</filter-name>
  <filter-class>com.blah.BlahBlahFilter</filter-class>
</filter>

<filter-mapping>
  <filter-name>blahBlahFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>


<servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

spring-mvc.xml:

  <context:annotation-config/>
  <context:component-scan base-package="com.blah"/>   
  <mvc:annotation-driven/>
Was it helpful?

Solution

When you declare a Filter like so

<filter>
    <filter-name>blahBlahFilter</filter-name>
    <filter-class>com.blah.BlahBlahFilter</filter-class>
</filter>

you are telling the Servlet container to initialize it, not Spring. Therefore Spring does not manage its lifecyle and can not autowire anything into it. You might have a BlahBlahFilter bean in your context, but it won't be the one registered with the Servlet container.

Use a DelegatingFilterProxy or do your filter registration in a WebApplicationInitializer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top