SpringBoot中.properties文件绑定
两种方式
1、方式一:@ConfigurationProperties + @Component
- @ConfigurationProperties是springboot提供读取配置文件的一个注解
- @component是spring中的一个注解,它的作用是实现bean的注入
示例:
/**
* 方式一:
* 1、只有在容器中的组件才会拥有 SpringBoot提供的强大功能,所以用@Component 先把他放在容器中
2、mycar是在 application.properties文件中自己命名的
mycar.brand=BYD
mycar.price=100000
*/
@Data
@Component
@ConfigurationProperties(prefix = "mycar")
public class Car {
private String brand;
private Integer price;
}
application.properties文件
server.port=8080
mycar.brand=BYD
mycar.price=100000
debug=true
这里运行出来,就可以在页面上获取到 car的 值了
2、方式二:@EnableConfigurationProperties+ @ConfigurationProperties
- @EnableConfigurationProperties注解的作用是:使 某个使用 @ConfigurationProperties 注解的类生效
- @ConfigurationProperties是springboot提供读取配置文件的一个注解
示例:
/**
* 方式二:
* 2、得在配置类中写,让Car里面@ConfigurationProperties(prefix = "mycar")这个属性配置生效
注意:这个prefix 必须小写,不然会报错 (配置类就是 配置 注入bean的类)
*/
@Data
//@Component
@ConfigurationProperties(prefix = "mycar")
public class Car {
private String brand;
private Integer price;
}