“Spring Boot @ConfigurationProperties 配置绑定”的版本间的差异
跳到导航
跳到搜索
Jihongchang(讨论 | 贡献) |
Jihongchang(讨论 | 贡献) |
||
第82行: | 第82行: | ||
} | } | ||
+ | } | ||
+ | </syntaxhighlight>http 请求 http://localhost:8888/car<nowiki/>,得到<syntaxhighlight lang="json"> | ||
+ | { | ||
+ | "brand": "BYD", | ||
+ | "price": 100000 | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> |
2023年2月13日 (一) 05:51的版本
https://www.bilibili.com/video/BV19K4y1L7MT/?p=12
旧的 properties 文件参数读取封装到 Java Bean
public class getProperties {
public static void main(String[] args) throws IOException {
Properties pps = new Properties();
pps.load(new FileInputStream("a.properties"));
Enumeration<?> enumeration = pps.propertyNames(); //得到配置文件的名字
while (enumeration.hasMoreElements()) {
String strKey = (String) enumeration.nextElement();
String strValue = pps.getProperty(strKey);
System.out.println(strKey + "=" + strValue);
/**
* 封装到 Java Bean
* ……
*/
}
}
}
使用 @ConfigurationProperties
/**
* 只有在容器中的组件,才会拥有 Spring Boot 提供的强大功能
*/
@Component
@ConfigurationProperties(prefix = "mycar")
public class Car {
private String brand;
private Integer price;
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
@Override
public String toString() {
return "Car{" +
"brand='" + brand + '\'' +
", price=" + price +
'}';
}
}
application.yaml
mycar:
brand: BYD
price: 100000
@RestController
public class HelloController {
@Autowired
Car car;
@RequestMapping("/car")
public Car car() {
return car;
}
}
http 请求 http://localhost:8888/car,得到
{
"brand": "BYD",
"price": 100000
}