Spring Boot 讀取properties檔案中的屬性值2種方式(@ConfigurationProperties、@Value)
阿新 • • 發佈:2021-02-04
技術標籤:Spring Boot
1 properties檔案配置
car.brand=BYD
car.price=100000
2讀取properties檔案中的屬性值
2.1 @ConfigurationProperties
@ConfigurationProperties可以讀取所有字首為car的屬性,並將properties屬性值裝配給跟相同屬性名的Car例項成員。
package com.entity; @Component @ConfigurationProperties(prefix = "car") public class Car { private String brand; private String price; public Car() { } public Car(String brand, String price) { this.brand = brand; this.price = price; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } }
2.2 @Value
@Value可以單個屬性的值裝配給Car例項成員,裝配時不要求屬性名和例項成員名相同。
package com.entity; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class Car { @Value("${car.brand}") private String brand; @Value("${car.price}") private String price; public Car() { } public Car(String brand, String price) { this.brand = brand; this.price = price; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } }
3 Controller
package com.controller; import com.entity.Car; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class PageController { @Autowired private Car car; @RequestMapping("/car") public Car car(){ return car; } }
4 頁面除錯
注:使用@ConfigurationProperties註解之前要先加入@Component註解。