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內容


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM