1.@ConfigurationProperties形式
2.@EnableConfigurationProperties形式
3.@Component+@ConfigurationProperties形式
第一种:@ConfigurationProperties形式(举例)
原文链接:https://blog.csdn.net/yingxiake/article/details/51263071
@SpringBootApplication
public class DemoApplication{
//...
@Bean
@ConfigurationProperties(prefix = "connection")
public ConnectionSettings connectionSettings(){
return new ConnectionSettings();
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
第一种:@EnableConfigurationProperties(举例)必须在配置类当中使用才能生效,因为它在容器中组件
配置文件 application.properties:
mycar.brand=aodi
mycar.price=430000
@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 +
'}';
}
}
配置类加入这个注解:
@EnableConfigurationProperties(Car.class)
//开启谁的属性配置功能
//把car组件自动注册容器中(开启配置绑定功能)此时就不用使用@Component注解了
第三种:@Component+@ConfigurationProperties形式(举例)
通过使用@ConfigurationProperties和@Component注解自定义参数配置类,程序启动时将自动加载application.properties配置文件中的对应的配置项
java bean和配置文件绑定:示例代码:
配置文件 application.properties:
mycar.brand=aodi
mycar.price=430000
bean class
@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 +
'}';
}
}
@RestController
@RequestMapping("/api")
public class HomeController {
private static final Logger homeLogger = LoggerFactory.getLogger(HomeController.class);
@Autowired
Car car;
@RequestMapping("/car")
public Car getcar() {
homeLogger.info("### 获取配置文件的配置 ======================");
return car;
}
}
测试: