springboot读取自定义properties配置文件方法

推荐两种方法 主要springboot项目注解更加方便使用
一.使用@PropertySource 方法

springboot项目resources层下创建XXX.properties 文件

properties文件内容

准备工作完成~
在springboot项目里使用@PropertySource注解来导入properties文件到使用类中
经过@Value标签获取到properties文件的数值参数

如此操作把properties文件参数数据引入使用类中
二.使用@ConfigurationProperties和@PropertySource 方法

使用ConfigurationProperties和PropertySource 把properties文件内容映射到对象实体类中,经实体类调用获取到properties参数
详见~
1.创建一个properties 文件


2.写入参数

plc.data1=${random.int(10)}

3.创建实体类对应properties文件内容

`
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import lombok.Data;

/**

  • @author :Rogue programmer
  • @version 创建时间:2020年6月15日 下午9:34:59
  • 类说明
    */
    @Configuration //声明配置文件类
    @ConfigurationProperties(prefix = "plc", ignoreUnknownFields = false)//匹配properties前缀属性 ‘plc’,ignoreUnknownFields 不符合是抛出异常
    @PropertySource("classpath:config/plcdata1.properties")//指定properties文件的路径
    @Data//lombok组件
    @Component
    public class PlcTestEntity {
    private int data1;
    }

`
4.使用类调用PlcTestEntity 来获取properties内容

posted @ 2020-06-15 23:38  RunawayProgrammer  阅读(2250)  评论(0编辑  收藏  举报