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

发布时间 2023-09-08 14:52:29作者: rockdow

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

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

WebProperties.class中可以看到原因,在这个类被Spring容器管理时,会进行初始化操作,设置默认静态资源存放位置:

 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的配置底层方法。所以此时默认规则存在,自己配置的规则也存在。