首頁 > 軟體

SpringBoot讀取自定義組態檔方式(properties,yaml)

2022-07-08 14:04:20

一、讀取系統組態檔application.yaml

1、application.yaml組態檔中增加一下測試設定

testdata:
  animal:
    lastName: 動物
    age: 18
    boss: true
    birth: 2022/02/22
    maps: {key1:value1,key2:value2}
    list: [dog,cat,house]
    dog:
      name: 旺財
      age: 3

2、新建entity實體類Animal

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Component//標識為Bean
@ConfigurationProperties(prefix = "testdata.animal")//prefix字首需要和yml組態檔裡的匹配。
@Data//這個是一個lombok註解,用於生成getter&setter方法
public class Animal {
    private String lastName;
    private int age;
    private boolean boss;
    private Date birth;
    private Map<String,String> maps;
    private List<String> list;
    private Dog dog;
}

3、新建entity實體類dog

package com.example.demo.db.config;
import lombok.Data;
import org.springframework.stereotype.Component;
@Component//標識為Bean
@Data//這個是一個lombok註解,用於生成getter&setter方法
@Configuration//標識是一個設定類
public class Dog {
    private String name;
    private int age;
}

4、新建測試類MyTest

import com.example.demo.db.config.RemoteProperties;
import junit.framework.TestCase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)//讓測試執行於Spring測試環境
@SpringBootTest(classes = DemoApplication.class)//指定啟動類
@EnableConfigurationProperties(RemoteProperties.class)//使RemoteProperties註解類生效
public class MyTests {
    @Autowired
    Animal animal;
    @Test
    public void test2() {
        System.out.println("person===="+animal);
        System.out.println("age======="+animal.getAge());
        System.out.println("dog.name======="+animal.getDog().getName()+" dog.age===="+animal.getDog().getAge());
    }
}

5、執行結果:

二、讀取自定義組態檔properties格式內容

1、resourcesconfig目錄下新建remote.properties組態檔,內容如下:

remote.testname=張三
remote.testpass=123456
remote.testvalue=ceshishuju

2、新建entity實體類RemoteProperties

package com.example.demo.db.config;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Configuration//表明這是一個設定類
@ConfigurationProperties(prefix = "remote",ignoreInvalidFields = false)//該註解用於繫結屬性。prefix用來選擇屬性的字首,也就是在remote.properties檔案中的「remote」,ignoreUnknownFields是用來告訴SpringBoot在有屬性不能匹配到宣告的域時丟擲異常。
@PropertySource(value="classpath:config/remote.properties",ignoreResourceNotFound = false)//組態檔路徑
@Data//這個是一個lombok註解,用於生成getter&setter方法
@Component//標識為Bean
public class RemoteProperties {
    private String testname;
    private String testpass;
    private String testvalue;
}

3、新建測試類MyTests

import com.example.demo.db.config.RemoteProperties;
import junit.framework.TestCase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)//讓測試執行於Spring測試環境
@SpringBootTest(classes = DemoApplication.class)//指定啟動類
@EnableConfigurationProperties(RemoteProperties.class)//應用組態檔類,使RemoteProperties註解類生效
public class MyTests {
    @Autowired
    RemoteProperties remoteProperties;
    @Test
    public void test2() {
        TestCase.assertEquals(1, 1);
        String testpass=remoteProperties.getTestpass();
        System.out.println("-----------:"+testpass);
        System.out.println("------------:"+remoteProperties.getTestvalue());
    }
}

4、執行結果:

三、讀取自定義組態檔yaml格式內容

1、resourcesconfig目錄下新建remote.yaml組態檔,內容如下:

remote:
  person:
    testname: 張三
    testpass: 123456
    testvalue: kkvalue

2、新建工廠轉換類PropertySourceFactory

package com.example.demo.db.config;
import org.apache.logging.log4j.core.config.yaml.YamlConfigurationFactory;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;
import java.io.IOException;
//把自定義組態檔.yml的讀取方式變成跟application.yml的讀取方式一致的 xx.xx.xx
public class MyPropertySourceFactory implements PropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource encodedResource) throws IOException {
        return new YamlPropertySourceLoader().load(name,encodedResource.getResource()).get(0);
    }
}

3、新建entity實體類RemoteProperties

package com.example.demo.db.config;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Configuration//表明這是一個設定類
@ConfigurationProperties(prefix = "remote",ignoreInvalidFields = false)//該註解用於繫結屬性。prefix用來選擇屬性的字首,也就是在remote.properties檔案中的「remote」,ignoreUnknownFields是用來告訴SpringBoot在有屬性不能匹配到宣告的域時丟擲異常。
@PropertySource(value="classpath:config/remote.yaml",factory = MyPropertySourceFactory.class)//組態檔路徑,設定轉換類
@Data//這個是一個lombok註解,用於生成getter&setter方法
@Component//標識為Bean
public class RemoteProperties {
    @Value("${remote.person.testname}")//根據組態檔寫全路徑
    private String testname;
    @Value("${remote.person.testpass}")
    private String testpass;
    @Value("${remote.person.testvalue}")
    private String testvalue;
 
}

4、新建測試類MyTests

import com.example.demo.db.config.RemoteProperties;
import junit.framework.TestCase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)//讓測試執行於Spring測試環境
@SpringBootTest(classes = DemoApplication.class)//指定啟動類
@EnableConfigurationProperties(RemoteProperties.class)//使RemoteProperties註解類生效
public class MyTests {
    @Autowired
    RemoteProperties remoteProperties;
    @Test
    public void test2() {
        TestCase.assertEquals(1, 1);
        String testpass=remoteProperties.getTestpass();
        System.out.println("asdfasdf"+testpass);
        System.out.println("asdfasdf"+remoteProperties.getTestvalue());
    }
}

5、執行結果:

 說明:

 這裡需要寫一個工廠去讀取propertySource(在偵錯的時候我看到預設讀取的方式是xx.xx.xx而自定義的yml組態檔是每一個xx都是分開的,所以不能獲取到,而自己建立的設定類MyPropertySourceFactory就是需要把自定義組態檔.yml的讀取方式變成跟application的讀取方式一致的 xx.xx.xx,並且通過@Value註解指定變數的的關係和yaml組態檔對應)

四、其他擴充套件內容

可以加入依賴spring-boot-configuration-processor後續寫組態檔就有提示資訊:

<!-- 匯入檔案處理器,加上這個,以後編寫設定就有提示了-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId> spring-boot-configuration-processor</artifactId>
    <optional> true </optional>
</dependency>

其他獲取設定相關內容後續更新。

以上為個人經驗,希望能給大家一個參考,也希望大家多多支援it145.com。


IT145.com E-mail:sddin#qq.com