@ConfigurationProperties
主要作用就是将prefix
属性指定的前缀配置项的值绑定到这个Bean上,默认情况下需要和@Component
或者@Configuration
一起使用才能生效。
首先回忆以下使用Java如何读取properties文件中的内容,会看到使用起来会很麻烦,SpringBoot给我们提供了更简单的方式读取Properties配置项内容。
public class getProperties {
public static void main(String[] args) throws FileNotFoundException, IOException {
Properties pps = new Properties();
pps.load(new FileInputStream("a.properties"));
Enumeration enum1 = pps.propertyNames();//得到配置文件的名字
while(enum1.hasMoreElements()) {
String strKey = (String) enum1.nextElement();
String strValue = pps.getProperty(strKey);
System.out.println(strKey + "=" + strValue);
//封装到JavaBean。
}
}
}
方式一
当配置文件中有前缀为mycar的配置内容时,会自动将其注入组件中
注意:只有在容器中的组件,才会拥有SpringBoot提供的强大功能,所以添加了@Component注解
@Data
@Component
@ConfigurationProperties(prefix = "mycar")
public class Car {
private String brand;
private Integer price;
}
application.properties配置内容
mycar.brand=BYD
mycar.price=100000
通过controller层获取对象
RestController
public class HelloController {
@Autowired
Car car;
@RequestMapping("/car")
public Car car(){
return car;
}
}
成功注入对象里面
方式二
场景:如果我们使用的是第三方jar包,就不能自己添加@Component注解,需要使用新的方式
@Data
@ConfigurationProperties(prefix = "mycar")
public class Car {
private String brand;
private Integer price;
}
@EnableConfigurationProperties有两个作用:
- 开启Car配置绑定功能
- 把这个Car组件自动注入到容器中
@Configuration
@EnableConfigurationProperties(Car.class)
public class MyConfig {
}