技術(shù)棧:SpringBoot 1.5+
在項目根目錄 springboot-learning-example,運行 maven 指令:
cd springboot-learning-example
mvn clean install
運行 springboot-properties 工程 org.spring.springboot.property.PropertiesTest 測試類的 getHomeProperties 方法??梢栽诳刂婆_看到輸出,這是通過自定義屬性獲取的值:
HomeProperties{province='ZheJiang', city='WenLing', desc='dev: I'm living in ZheJiang WenLing.'}
首先項目結(jié)構(gòu)如下:
├── pom.xml
└── src
├── main
│ ├── java
│ │ └── org
│ │ └── spring
│ │ └── springboot
│ │ ├── Application.java
│ │ └── property
│ │ ├── HomeProperties.java
│ │ └── UserProperties.java
│ └── resources
│ ├── application-dev.properties
│ ├── application-prod.properties
│ └── application.properties
└── test
├── java
│ └── org
│ └── spring
│ └── springboot
│ └── property
│ ├── HomeProperties1.java
│ └── PropertiesTest.java
└── resouorces
└── application.yml
在 application.properties 中對應(yīng) HomeProperties 對象字段編寫屬性的 KV 值:
## 家鄉(xiāng)屬性 Dev
home.province=ZheJiang
home.city=WenLing
home.desc=dev: I'm living in ${home.province} ${home.city}.
然后,編寫對應(yīng)的 HomeProperties Java 對象:
/**
* 家鄉(xiāng)屬性
*
* Created by bysocket on 17/04/2017.
*/
@Component
@ConfigurationProperties(prefix = "home")
public class HomeProperties {
/**
* 省份
*/
private String province;
/**
* 城市
*/
private String city;
/**
* 描述
*/
private String desc;
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
@Override
public String toString() {
return "HomeProperties{" +
"province='" + province + '\'' +
", city='" + city + '\'' +
", desc='" + desc + '\'' +
'}';
}
}
如果不是用 application.properties 文件,而是用 application.yml 的文件,對應(yīng)配置如下:
## 家鄉(xiāng)屬性
home:
province: 浙江省
city: 溫嶺松門
desc: 我家住在${home.province}的${home.city}
運行 springboot-properties 工程 org.spring.springboot.property.PropertiesTest 測試類的 randomTestUser 方法。多次運行,可以發(fā)現(xiàn)每次輸出不同 User 屬性值:
UserProperties{id=-3135706105861091890, age=41, desc='泥瓦匠叫做3cf8fb2507f64e361f62700bcbd17770', uuid='582bcc01-bb7f-41db-94d5-c22aae186cb4'}
application.yml 方式的配置如下( application.properties 形式這里不寫了):
## 隨機屬性
user:
id: ${random.long}
age: ${random.int[1,200]}
desc: 泥瓦匠叫做${random.value}
uuid: ${random.uuid}
application-dev.properties:開發(fā)環(huán)境
application-prod.properties:生產(chǎn)環(huán)境
Spring Boot 是通過 application.properties 文件中,設(shè)置 spring.profiles.active 屬性,比如 ,配置了 dev ,則加載的是 application-dev.properties :
# Spring Profiles Active
spring.profiles.active=dev
那運行 springboot-properties 工程中 Application 應(yīng)用啟動類,從控制臺中可以看出,是加載了 application-dev.properties 的屬性輸出:
HomeProperties{province='ZheJiang', city='WenLing', desc='dev: I'm living in ZheJiang WenLing.'}
更多建議: