springboot使用自定义配置文件

来源:互联网 发布:deb ubuntu 安装 编辑:程序博客网 时间:2024/05/17 22:20

由于高版本的springboot去掉了@configurationProperties中的location参数,然后在网上查了一些资料,总结了以下两种方法使用自定义的配置文件:

1. 第一种方法:

参考:https://segmentfault.com/q/1010000006828771?_ea=1144561

(1)在resource目录下创建测试用的yml配置文件

myconfig:  test: 123

(2)创建bean文件

@Component//使用@Configuration也可以@ConfigurationProperties(prefix = "myconfig")//前缀@PropertySource(value = "classpath:myconfig.yml")//配置文件路径public class MyConfig {   @Value("${test}")//需要使用@value注解来注入,否则是null    private String test;    public String getTest() {        return test;    }    public void setTest(String test) {        this.test = test;    }}

注:在网上看到的使用方法中,有很多并没有使用@Value注解,但是在本地测试发现(也尝试了@EnableConfigurationProperties注解,但是并不好用)如果不在属性上使用@value注解,总是null


(3)主函数

@SpringBootApplicationpublic class ConfigApplication implements CommandLineRunner{@Autowiredprivate MyConfig myconfig;public static void main(String[] args) {SpringApplication.run(ConfigApplication.class, args);}@Overridepublic void run(String... strings) throws Exception {System.out.println(myconfig.getTest());}}
输出:123


2.第二种方法:

来自:github 作者:gabrieledarrigo  https://github.com/spring-projects/spring-boot/issues/6726

(1)创建YamlPropertySourceFactory继承PropertySourceFactory

public class YamlPropertySourceFactory implements PropertySourceFactory{    @Override    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {        return name != null ? new PropertySourcesLoader().load(resource.getResource(), name, null) : new PropertySourcesLoader().load(                resource.getResource(), getNameForResource(resource.getResource()), null);    }    private static String getNameForResource(Resource resource) {        String name = resource.getDescription();        if (!org.springframework.util.StringUtils.hasText(name)) {            name = resource.getClass().getSimpleName() + "@" + System.identityHashCode(resource);        }        return name;    }}

(2)指定factory为刚才创建的YamlPropertySourceFactory,用此方法不需要使用@Value即可实现属性的自动注入

@Component@ConfigurationProperties(prefix = "myconfig")@PropertySource(value = "classpath:myconfig.yml",factory=YamlPropertySourceFactory.class)//指定factorypublic class MyConfig {    private String test;    public String getTest() {        return test;    }    public void setTest(String test) {        this.test = test;    }}