SpringBoot @PropertySource自定义配置yml文件

有时候同一类配置需要单独使用一个配置文件,这个注解`@PropertySource`可以简单快速的实现。

Posted by youthred on May 20, 2022

有时候同一类配置需要单独使用一个配置文件,这个注解@PropertySource可以简单快速的实现。

1
@PropertySource(value = {"classpath:custom.properties"})

对于YAML格式也是可以解析的,但需要实现PropertySourceFactory

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package io.github.youthred.es.cleaner.conf;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;

import java.io.IOException;
import java.util.Objects;

public class YamlPropertySourceFactory implements PropertySourceFactory {

    @Override
    public PropertySource<?> createPropertySource(String s, EncodedResource encodedResource) throws IOException {
        YamlPropertiesFactoryBean factoryBean = new YamlPropertiesFactoryBean();
        factoryBean.setResources(encodedResource.getResource());
        return new PropertiesPropertySource(encodedResource.getResource().getFilename(), Objects.requireNonNull(factoryBean.getObject()));
    }
}

然后在注解上指明。

1
2
3
4
@PropertySource(
    factory = YamlPropertySourceFactory.class,
    value = {"classpath:custom.yml"}
)

建议再加上注解@ConfigurationProperties(prefix = "conf")指明前缀,不建议使用org.springframework.beans.factory.annotation.Value来绑定配置。

配置文件就是拿来修改的,以上的自定义配置在打包后便难以更改,好在该注解的value属性还提供了另一种路径解析方式file

在项目根目录与src平级上新增目录config,移入自定义配置文件,修改value属性值自定义配置路径。

1
value = {"file:./config/custom.yml"}

再次打包,新建jar包的平级目录config,放入自定义配置文件,这样更改后的配置无需重新打包即可生效。


SpringBoot的配置读取优先顺序(优先级递减)为:

  1. 根目录下config

  2. 根目录

  3. classpathconfig

  4. classpath

.properties的优先级大于.yml