SpringBoot 2.0 编程方式配置,不使用默认配置方式
SpringBoot的一般配置是直接使用application.properties或者application.yml,因为SpringBoot会读取.perperties和yml文件来覆盖默认配置;
从源码分析SpringBoot默认配置是怎样的
ResourceProperties
这个class说明了springboot默认读取的properties
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
"classpath:/META-INF/resources/", "classpath:/resources/",
"classpath:/static/", "classpath:/public/" };
WebMvcAutoConfiguration
这个class就是springboot默认的mvc配置类,里面有一个static class实现了WebMvcConfigurer
接口,;具体这个接口有什么用,具体可以看spring官网[springMVC配置][1]
@Configuration
@Import(EnableWebMvcConfiguration.class)
@EnableConfigurationProperties({ WebMvcProperties.class, ResourceProperties.class })
@Order(0)
public static class WebMvcAutoConfigurationAdapter
implements WebMvcConfigurer, ResourceLoaderAware
可以看到里面的默认viewResolver配置,只要我们复写了ViewResolver这个bean,就相当于不适用SpringBoot的默认配置;
@Bean
@ConditionalOnMissingBean
public InternalResourceViewResolver defaultViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix(this.mvcProperties.getView().getPrefix());
resolver.setSuffix(this.mvcProperties.getView().getSuffix());
return resolver;
}
这里里面有一个很常见的mapping,在springboot启动日志中就可以看到。
@Bean
public SimpleUrlHandlerMapping faviconHandlerMapping() {
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
mapping.setOrder(Ordered.HIGHEST_PRECEDENCE + 1);
mapping.setUrlMap(Collections.singletonMap("**/favicon.ico",
faviconRequestHandler()));
return mapping;
}
```
实验证明,通过实现了`WebMvcConfigurer`接口的bean具有优先级 (或者继承`WebMvcConfigurationSupport`),会覆盖在.properties中的配置。比如`ViewResolver`
### 编程方式配置SpringBoot例子
2种方式,1是实现`WebMvcConfigurer `接口,2是继承`WebMvcConfigurationSupport`;(其实还有第三种,就是继承`WebMvcConfigurerAdapter`,但是这种方式在Spring 5中被舍弃)
[1]: https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html