Thursday, January 15, 2015

Spring Security Filter Name and Bean Name

Name Matching

I read some code of an application that uses Spring security library. It has a class to implement the standard javax.servlet.Filter class. And this filter is declared as a bean in the application context xml files for Spring. The bean name is just assumed to be "xyz" here. But this filter is NOT declared in the web.xml file. Normally, in order for a filter class to be invoked, it has to be declared in the web.xml file. But in this application, the web.xml file only declares a filter with the name "xyz" for org.springframework.web.filter.DelegatingFilterProxy. The surprising thing is that the bean "xyz" in the application context IS invoked. After doing some searching, I found the following document that explains the puzzle.

When using servlet filters, you obviously need to declare them in your web.xml, or they will be ignored by the servlet container. In Spring Security, the filter classes are also Spring beans defined in the application context and thus able to take advantage of Spring's rich dependency-injection facilities and lifecycle interfaces. Spring's DelegatingFilterProxy provides the link between web.xml and the application context.

When using DelegatingFilterProxy, you will see something like this in the web.xml file:



Notice that the filter is actually a DelegatingFilterProxy, and not the class that will actually implement the logic of the filter. What DelegatingFilterProxy does is delegate the Filter's methods through to a bean which is obtained from the Spring application context. This enables the bean to benefit from the Spring web application context lifecycle support and configuration flexibility. The bean must implement javax.servlet.Filter and it must have the same name as that in the filter-name element. Read the Javadoc for DelegatingFilterProxy for more information



No comments:

Post a Comment