sprintboot读取自定义配置文件properties、yml、yaml,环境springboot2.4.4

我这里使用的是springboot2.4.4的版本,其他版本自测

在要赋值的Bean类上面添加注解,prefix是你配置的前缀

@ConfigurationProperties(prefix = "alipay")

再添加注解,注意是@PropertySource 不是@PropertySources,最后没有s

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

然后添加@Comment注解添加到IOC容器中,使用@Autowired或者@Resource注解注入使用

 

 

如果是yml或yaml的配置文件

就添加一个格式转换的类,如下

import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;

import java.io.IOException;
import java.util.List;
import java.util.Properties;

public class YamlAndPropertySourceFactory extends DefaultPropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        if (resource == null) {
            return super.createPropertySource(name, resource);
        }
        Resource resourceResource = resource.getResource();
        if (!resourceResource.exists()) {
            return new PropertiesPropertySource(null, new Properties());
        } else if (resourceResource.getFilename().endsWith(".yml") || resourceResource.getFilename().endsWith(".yaml")) {
            List<PropertySource<?>> sources = new YamlPropertySourceLoader().load(resourceResource.getFilename(), resourceResource);
            return sources.get(0);
        }
        return super.createPropertySource(name, resource);
    }
}

然后把@PropertySource中添加一个factory属性

@PropertySource(factory = YamlAndPropertySourceFactory.class,value = {"classpath:yml/alipay.yaml"})

 

Guess you like

Origin blog.csdn.net/qq_41890624/article/details/115404379