Spring Boot 项目中读取,加载,自定义配置文件,绑定到相应对象上。

一:pom.xml文件添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

二:创建自定义配置文件 person.properties

内容:

person.age=18
person.name=名字
person.birth=1994

三:创建配置文件绑定对象类 Person

/**
 *@ClassName Person
 *@Description @PropertySource 这个注解表示读取项目环境下的person.properties 文件
 * 而这个注解@ConfigurationProperties 表示 映射到前缀是person开头的配置
 * 如果没有设置 @PropertySource注解,则默认读取spring boot 的默认配置文件 application.properties
 * 而且@PropertySource注解 不支持.yml 类型的配置文件
 *@Author Ni Klaus
 *@Date 2019/10/5 0005 上午 11:26
 *@Version 1.0
 */
@PropertySource(value = {"classpath:person.properties"})
@ConfigurationProperties(prefix = "person")
@Component
@Data
public class Person {

    private String name;

    private int age;

    private String birth;
}

四:用spring boot 的单元测试类进行测试

测试结果:

 

拓展:

person.yml内容

person:
  age: 19
  name: 名字2
  birth: 1996

 

@PropertySource注解 不支持.yml 类型的配置文件

@PropertySource 不支持yml文件的对象转换,原因如下,看源码:他的默认构造工厂是PropertySourceFactory

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(PropertySources.class)
public @interface PropertySource {
    String name() default "";

    String[] value();

    boolean ignoreResourceNotFound() default false;

    String encoding() default "";

    Class<? extends PropertySourceFactory> factory() default PropertySourceFactory.class;
}

而PropertySourceFactory默认就一个实现:实现properties配置文件的加载解析

public class DefaultPropertySourceFactory implements PropertySourceFactory {
    public DefaultPropertySourceFactory() {
    }

    public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException {
        return name != null ? new ResourcePropertySource(name, resource) : new ResourcePropertySource(resource);
    }
}

所以,我们只要实现一个yml文件的工厂类就可以了

代码实现:

package com.sgl.springbootconfig.yaml;

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 org.springframework.lang.Nullable;

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

/**
 *@ClassName YamlPropertySourceFactory
 *@Description TODO
 *@Author Ni Klaus
 *@Date 2019/10/8 0008 下午 17:53
 *@Version 1.0
 */
public class YamlPropertySourceFactory implements PropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException {
        Properties propertiesFromYaml = loadYamlIntoProperties(resource);
        String sourceName = name != null ? name : resource.getResource().getFilename();
        return new PropertiesPropertySource(sourceName, propertiesFromYaml);
    }

    private Properties loadYamlIntoProperties(EncodedResource resource) throws FileNotFoundException {
        try {
            YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
            factory.setResources(resource.getResource());
            factory.afterPropertiesSet();
            return factory.getObject();
        } catch (IllegalStateException e) {
            // for ignoreResourceNotFound
            Throwable cause = e.getCause();
            if (cause instanceof FileNotFoundException)
                throw (FileNotFoundException) e.getCause();
            throw e;
        }
    }
}

绑定的时候用:

@PropertySource(factory = YamlPropertySourceFactory.class, value = "classpath:person.yml")
@ConfigurationProperties(prefix = "person")
@Component
@Data

测试结果:

亲测成功!!!

参考地址:https://mdeinum.github.io/2018-07-04-PropertySource-with-yaml-files/

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值