SpringBoot配置文件的读取

258 阅读1分钟

SpringBoot配置文件的读取

1.yml文件的读取

在要读取的配置文件中属性的Bean上添加如下注解:

@Component
@ConfigurationProperties(prefix= "前缀")
@Data

2.properties配置文件的读取

不是以application命名的配置文件,或者不是application命名的yml配置文件属性的读取

在要读取的配置文件中属性的Bean上添加如下注解:

@Configuration
@PropertySource("classpath:wxpay.properties") //读取配置文件
@ConfigurationProperties(prefix="wxpay") //读取wxpay节点
@Data //使用set方法将wxpay节点中的值填充到当前类的属性中

举例:

@Configuration
@PropertySource("classpath:wxpay.properties") //读取配置文件
@ConfigurationProperties(prefix="wxpay") //读取wxpay节点
@Data //使用set方法将wxpay节点中的值填充到当前类的属性中
public class WxPayConfig {

    // 商户号
    private String mchId;

    // 商户API证书序列号
    private String mchSerialNo;

    // 商户私钥文件
    private String privateKeyPath;

    // APIv3密钥
    private String apiV3Key;

    // APPID
    private String appid;

    // 微信服务器地址
    private String domain;

    // 接收结果通知地址
    private String notifyDomain;

}

3.将非springboot配置文件配置为springboot可识别的配置文件

image.png

image.png

image.png

image.png

image.png

  1. 可以帮助我们生成自定义配置的元数据信息,让配置文件和Java代码之间的对应参数可以自动定位,方便开发。
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
        <optional>true</optional>
    </dependency>