How to specify filter execution order using Spring Java configuration?

I have the following code snippet in my initializer:

public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Filter[] getServletFilters() { DelegatingFilterProxy shiroFilter = new DelegatingFilterProxy("shiroFilter"); shiroFilter.setTargetFilterLifecycle(true); return new Filter[]{new CorsFilter(),shiroFilter}; } } 

I want CorsFilter run before ShiroFilter . However, the Spring documentation does not indicate that the order in which filters are executed is determined by their order in the returned array.

If so, can someone clarify this? If not, can anyone suggest how I can guarantee the order in which the filters are executed?

+7
java spring spring-java-config
source share
3 answers

Just to keep the question updated.

Use spring @Order - Annotation

 @Component(value = "myCorsFilter") @Order(Ordered.HIGHEST_PRECEDENCE) public class CorsFilter implements Filter { [...] } public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return new Class[] { AppConfiguration.class }; } @Override protected Class<?>[] getServletConfigClasses() { return null; } @Override protected String[] getServletMappings() { return new String[] { "/" }; } @Override protected Filter[] getServletFilters() { return new Filter[] { new DelegatingFilterProxy("myEncodingFilter"), new DelegatingFilterProxy("myCorsFilter"), // or just new CorsFilter() new DelegatingFilterProxy("mySecurityFilter") //... }; } } 
+7
source share

Filters are registered in array order .

This causes ServletContext.addFilter() called in element order however . I am not sure if this actually leads to the filters being executed by the container in the order in which they were registered.

Tomcat, for example, uses HashMap to store filters , so I did not expect the filters to run in the order in which they were added.

Spring provides org.springframework.web.filter.CompositeFilter , so I would just return one CompositeFilter containing the two filters that you really want to use.

+4
source share

For those who might want to use the javax annotation instead of the spring order, the @javax.annotation.Priority annotation can also be used instead of @Order as the answer from "dit" above.

0
source share

All Articles