日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

SpringBoot 2.0 编程方式配置,不使用默认配置方式

發布時間:2025/7/14 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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配置

@Configuration@Import(EnableWebMvcConfiguration.class)@EnableConfigurationProperties({ WebMvcProperties.class, ResourceProperties.class })@Order(0)public static class WebMvcAutoConfigurationAdapterimplements WebMvcConfigurer, ResourceLoaderAware

可以看到里面的默認viewResolver配置,只要我們復寫了ViewResolver這個bean,就相當于不適用SpringBoot的默認配置;

@Bean@ConditionalOnMissingBeanpublic InternalResourceViewResolver defaultViewResolver() {InternalResourceViewResolver resolver = new InternalResourceViewResolver();resolver.setPrefix(this.mvcProperties.getView().getPrefix());resolver.setSuffix(this.mvcProperties.getView().getSuffix());return resolver;}

這里里面有一個很常見的mapping,在springboot啟動日志中就可以看到。

`java @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中被舍棄)

轉載于:https://www.cnblogs.com/chenjingquan/p/9194545.html

總結

以上是生活随笔為你收集整理的SpringBoot 2.0 编程方式配置,不使用默认配置方式的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。