我有以下問題:我想從.properties檔案中讀取一些值(產品的價格)。
但是我正在嘗試,它總是0.00作為一個價值。
這是我的服務 bean,我想在其中創建一個產品串列:
@Service
@ConfigurationProperties(prefix = "product-service")
public class ProductService {
private double first;
private double second;
private double third;
public double getFirst() {
return first;
}
public void setFirst(double first) {
this.first = first;
}
public double getSecond() {
return second;
}
public void setSecond(double second) {
this.second = second;
}
public double getThird() {
return third;
}
public void setThird(double third) {
this.third = third;
}
private List<ProductDTO> productList = Arrays.asList(
new ProductDTO(1, "Tomb Raider", first),
new ProductDTO(2, "10000 rp to lol", second),
new ProductDTO(3, "2k valorant points", third)
);
public List<ProductDTO> findAllProducts() {
return productList;
}
}
這是屬性檔案:
product-service.first = 225.00
product-service.second = 320.50
product-service.third = 150.99
uj5u.com熱心網友回復:
考慮到您使用 prefix = "product-service"
你應該宣告你的類欄位如下。
private double first;
private double second;
private double third;
您還應該更新 getter 和 setter。
您的代碼中還有另一個錯誤
private List<ProductDTO> productList = Arrays.asList(
new ProductDTO(1,"Tomb Raider",first),
new ProductDTO(2,"10000 rp to lol",second),
new ProductDTO(3,"2k valorant points",third)
);
當你的類被初始化時,這個欄位被初始化。但是 Spring 使用代理初始化您的 bean。因此,當類初始化時,您productList將擁有, ,的0值。firstsecondthird
如果你希望這個作業你應該更換
public List<ProductDTO> findAllProducts() {
return productList;
}
和
public List<ProductDTO> findAllProducts() {
return Arrays.asList(
new ProductDTO(1,"Tomb Raider",first),
new ProductDTO(2,"10000 rp to lol",second),
new ProductDTO(3,"2k valorant points",third)
);
}
uj5u.com熱心網友回復:
不要將您的配置屬性與服務層混合。
你有幾種方法:
- 創建一個單獨的配置類:
@ConfigurationProperties("product-service")
public class ProductProperties {
private Double first;
private Double second;
private Double third;
// getters & setters
}
并直接在您的服務類中使用它:
class ProductService {
private ProductProperties properties;
// use at code: properties.getFirst()
}
根據您的 Spring Boot 版本,您可能需要@EnableConfigurationProperties({ProductProperties.class})在任何標有@Configuration
- 使用
@Value:
class ProductService {
@Value("${product-service.first}")
private double first;
//...
}
你應該設定你的主類:
有用的鏈接:
- Spring Boot 中的 @ConfigurationProperties 指南
- Spring @Value 快速指南
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/412174.html
標籤:
上一篇:沒有使用webFlux和netty呼叫ReactiveCosmosRepository
下一篇:將非彈簧物件注入彈簧專案
