底层注解-配置绑定 @ConfigurationProperties
# 90.底层注解-配置绑定@ConfigurationProperties
注解 @ConfigurationProperties 可以读取到 properties 文件中的内容,并且把它封装到 JavaBean 中,以供随时使用
# 前言
我们经常将一些频繁变化的信息,放到配置文件中,例如数据库连接信息;
然后在项目启动的时候,就读取配置文件,并加载,还是比较麻烦的,需要手工读取和赋值:
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...........
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
当配置增多,那么代码就会更复杂,可能还得用正则;而在 SpringBoot 中就很方便。演示:
# 新增 Car
package com.peterjxl.boot.bean;
public class Car {
private String brand;
private Integer price;
}
1
2
3
4
5
6
2
3
4
5
6
getter 和 setter 自行生成
# 修改配置文件
我们在 application.properties 里增加汽车的配置:
server.port=9999
spring.servlet.multipart.max-file-size=10MB
mycar.brand=BYD
mycar.price=100000
1
2
3
4
5
2
3
4
5
# 增加注解
@Component
@ConfigurationProperties(prefix = "mycar")
public class Car {
1
2
3
2
3
说明:
- @Component:得是容器中的组件,才能完成配置绑定
- @ConfigurationProperties:指定了前缀
# 测试
我们新增一个 Controller 方法,返回 car 对象:
package com.peterjxl.boot.controller;
@RestController // @RestController = @Controller + @ResponseBody
public class HelloController {
@Autowired
Car car;
@RequestMapping("/car")
public Car car() {
return car;
}
@RequestMapping("/hello")
public String hello() {
return "你好, Spring Boot 2!";
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
访问 localhost: 9999/car (opens new window),可以看到对象的信息
# 第二种方法
我们还可以使用这个两个注解来完成配置绑定:
@EnableConfigurationProperties + @ConfigurationProperties
首先,我们在一个配置类上使用@EnableConfigurationProperties。注意,要传入 Car 对象的字节码,如:
@EnableConfigurationProperties(Car.class)
public class MyConfig {
1
2
2
然后,car 对象就不用@Component 注解了,配置类会自动导入 car 组件:
//@Component
@ConfigurationProperties(prefix = "mycar")
public class Car {
1
2
3
2
3
这样,我们就不用再使用@Component 注解了。这有什么用呢?有时候,我们要配置绑定的类,是第三方 jar 包的类,此时就可以用这种方式。
# 最后
在 SpringBoot 底层,我们会经常看到该注解
上次更新: 2024/10/3 10:01:52