Spring Boot 讀取組態檔
Spring Boot 讀取組態檔有兩種方式:
- 加載多個
@ConfigurationProperties(xxx) - 加載單個
@Value('${xxx}')
廢話不多說,直接上例子
加載多個配置項資訊
1、在springboot專案里的yml添加資訊
custom:
name: xxx
url: 192.168.0.168
app-version: 0.2
2、創建配置類
@Component
@ConfigurationProperties(prefix = "custom-config")
@Data
@ToString
public class CoustomConfig {
private String name;
private String url;
private String version;
}
3、測驗
@SpringBootTest
public class DemoTest {
@Autowired
private CoustomConfig coustomConfig;
@Test
public void test01(){
System.out.println(coustomConfig.toString());
}
}
結果:

加載單個配置項資訊
1、添加專案埠資訊
server:
port: 8089
2、獲取配置資訊,并測驗
@SpringBootTest
public class DemoTest {
@Value(value = "https://www.cnblogs.com/galenblog/p/${server.port}")
private String port;
@Test
public void test02(){
System.out.println(port);
}
}
結果:

擴展:
- springboot加載默認組態檔會有優先級,
- 所有的組態檔spring都會讀取,相互之間不會排斥,但是會覆寫,
- 相同配置項,高優先級組態檔的內容會覆寫低優先級的配置,低優先級配置不會生效,

小總結:
1、使用@ConfigurationProperties 需要搭配@Component來使用
2、使用@Value時,需要注意${},
3、@ConfigurationProperties支持松散系結,-,_會根據pojo自動轉換駝峰,例如:app-version系結時會轉換成appVersion,或者會轉換成appversion,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/472854.html
標籤:Java
