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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM