前言
本文记录基于Spring Boot 2.0.4
一、Spring MVC启用Web配置
在Spring MVC中,提供了自定义Web的配置方式,通过继承WebMvcConfigurerAdapter
,并使用@EnableWebMvc
开启对Spring MVC的配置支持。例:
@Configuration
@EnableWebMvc
@ComponentScan("com.test")
public class MyWebMvcConfig extneds WebMvcConfigurerAdapter {
@Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/classes/views");
viewResolver.setSuffix(".jsp");
viewResolver.setViewClass(JstlView.class);
return viewResolver;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/static")
.addResourceLocations("classpath:/public")
.addResourceLocations("classpath:/resources")
.addResourceLocations("classpath:/META-INF/resources");
}
}
上例中除了配置用于JSP的视图解析器InternalResourceViewResolver
外,
还配置了项目中静态资源对外的访问路径,
比如将index.html文件放置于以下目录之一:
- classpath:static/index.html
- classpath:public/index.html
- classpath:resources/index.html
- classpath:META-INF/resources/index.html
当访问应用跟目录如localhost:8080/时会直接映射。
二、Spring Boot启用Web配置
在Spring Boot中,则提供了对于Web的自动配置,不必手动配置,
这在于Spring Boot运作时的WebMvcAutoConfiguration
。
回归到@SpringBootApplication
,其中的核心是@EnableAutoConfiguration
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import({AutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {
String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";
Class<?>[] exclude() default {};
String[] excludeName() default {};
}
Spring Boot提供的Web自动配置有
1.ViewResolver配置,源码中如:
@Bean
@ConditionalOnMissingBean
public InternalResourceViewResolver defaultViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix(this.mvcProperties.getView().getPrefix());
resolver.setSuffix(this.mvcProperties.getView().getSuffix());
return resolver;
}
2.静态资源对外路径配置,源码中如:
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
} else {
Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
if (!registry.hasMappingForPattern("/webjars/**")) {
this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
}
String staticPathPattern = this.mvcProperties.getStaticPathPattern();
if (!registry.hasMappingForPattern(staticPathPattern)) {
this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
}
}
}
此后如果Spring Boot提供的Spring MVC默认配置不合需求,可以自定义配置MVC配置,通过前面的示例使用@Configuration
和@EnableWebMvc
。这种方法是实现对MVC完全独立的控制(覆盖配置),Spring Boot提供的MVC自动配置均无效。
保留Spring Boot自动配置的情况下,并存自定义MVC配置。
在之前的Spring Boot版本中可以通过定义一个配置类(@Configuration
)继承WebMvcConfigurerAdapter
(不使用@EnableWebMvc
),实现保留配置。
在Spring Boot 2.X版本中,自定义MVC配置则通过继承WebMvcConfigurerSupport
或实现WebMvcConfigurer
来实现,不再推荐WebMvcConfigurerAdapter
。
*继承WebMvcConfigurerSupport
的配置方式是覆盖配置,
*实现WebMvcConfigurer
的配置方式是保留配置。
在Spring Boot 2.X对MVC自动配置中,WebMvcAutoConfiguration
源码如下
@Configuration
@ConditionalOnWebApplication(
type = Type.SERVLET
)
@ConditionalOnClass({Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class})
@ConditionalOnMissingBean({WebMvcConfigurationSupport.class})
@AutoConfigureOrder(-2147483638)
@AutoConfigureAfter({DispatcherServletAutoConfiguration.class, ValidationAutoConfiguration.class})
public class WebMvcAutoConfiguration {
//......
}
其中的注解@ConditionalOnMissingBean
,限制了WebMvcAutoConfiguration
在找不到WebMvcConfigurerSupport
类型Bean时才生效,因此当存在自定义的WebMvcConfigurerSupport
配置时,Spring Boot提供的自动配置不生效。