SpringBoot中配置文件和配置类实现个性化配置的一点区别

先说配置文件,以properties文件为例,SpringBoot中默认存放静态资源文件夹路径是 "classpath:/META-INF/resources/", "classpath:/resources/","classpath:/static/","classpath:/public/"。经过下面配置后,这些默认规则都不再生效。

#自定义静态资源文件夹位置
spring.web.resources.static-locations=classpath:/a/,classpath:/b/,classpath:/static/

WebProperties.class中可以看到原因,在这个类被Spring容器管理时,会进行初始化操作,然后由SpringBoot中默认的WebMvcConfigurer实现类读取它的属性值来设置默认静态资源存放位置:

复制代码
 private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};
        private String[] staticLocations;
        private boolean addMappings;
        private boolean customized;
        private final Chain chain;
        private final Cache cache;
     //初始化时设置默认静态资源存放位置
        public Resources() {
            this.staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
            this.addMappings = true;
            this.customized = false;
            this.chain = new Chain();
            this.cache = new Cache();
        }
复制代码

但是当通过注解 @ConfigurationProperties("spring.web") 获取了我们配置的静态文件位置后,会利用set方法将 this.staticLocations  设置为我们指定的值,此时默认配置就不再生效;

再说配置类,如下:

复制代码
@Configuration //这是一个配置类
public class MyConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //保留以前规则
        //自己写新的规则。
        registry.addResourceLocations("classpath:/a/","classpath:/b/");
    }
}
复制代码

MyConfig类继承了WebMvcConfigurer,而DelegatingWebMvcConfiguration类利用 DI 把容器中 所有 WebMvcConfigurer 注入进来,SpringBoot又会调用 DelegatingWebMvcConfiguration的方法配置底层规则,而它调用所有 WebMvcConfigurer的配置底层方法。所以此时默认规则存在,自己配置的规则也存在。

 

 

posted @   rockdow  阅读(94)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示