Spring boot的@Configuration
就在我惊艳于spring 4的AbstractAnnotationConfigDispatcherServletInitializer小巧简洁(如下)的时候却发现spring boot下面竟然无效。
1 public class Initializer extends AbstractAnnotationConfigDispatcherServletInitializer { 2 3 @Override 4 protected String[] getServletMappings() { 5 return new String[] { "/" }; 6 } 7 8 @Override 9 protected Class<?>[] getRootConfigClasses() { 10 return new Class[] { TracingConfiguration.class, AppConfiguration.class }; 11 } 12 13 /** Ensures tracing is setup for all HTTP requests. */ 14 @Override 15 protected Filter[] getServletFilters() { 16 return new Filter[] { new DelegatingTracingFilter() }; 17 } 18 19 @Override 20 protected Class<?>[] getServletConfigClasses() { 21 // TODO Auto-generated method stub 22 return null; 23 } 24 }
后来经过调研发现其实是需要通过@Configuration(注意类级别注解)的类来进行处理,比如下例就是通过FilterRegistrationBean 来指定filter(相当于上面的getServletFilters函数):
1 @Configuration 2 public class AppConfiguration { 3 @Autowired 4 private AutowireCapableBeanFactory beanFactory; 5 6 @Bean 7 public FilterRegistrationBean myFilter() { 8 FilterRegistrationBean registration = new FilterRegistrationBean(); 9 Filter myFilter = new DelegatingTracingFilter(); 10 beanFactory.autowireBean(myFilter); 11 registration.setFilter(myFilter); 12 //registration.addUrlPatterns("/myfilterpath/*"); 13 return registration; 14 } 15 }
与之类似的还有下面的bean定义对应于原生Spring的servlet以及多个Filter:
1 @Bean 2 public ServletRegistrationBean dispatcherServlet() { 3 ServletRegistrationBean registration = new ServletRegistrationBean( 4 new DispatcherServlet(), "/"); 5 registration.setAsyncSupported(true); 6 return registration; 7 } 8 9 @Bean 10 public Filter compositeFilter() { 11 CompositeFilter compositeFilter = new CompositeFilter(); 12 compositeFilter.setFilters(ImmutableList.of(new CorsFilter(), shiroFilter)); 13 return compositeFilter 14 }