Spring Boot (三) 将配置自动封装到实体
1. 背景与结论
- 背景:很多时候我们需要将配置文件中的值取出来,封装为一个实体再进行使用,如果能自动帮我们封装好,那就省去了我们手动封装的麻烦了,大大节省了时间。
- 结论:我们可以使用Spring Boot中的@ConfigurationProperties注解来实现这个功能
2. 实现
下面我们就来具体实现一下吧。
2.1配置文件
application.properties
test.properties.userName=Admin
test.properties.email=test@test.com
test.properties.age=18
test.properties.url=http://localhost:8060/test/properties
2.2 封装配置信息实体编写
TestProperties.java
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "test.properties")
public class TestProperties {
private String userName;
private String email;
private Integer age;
private String url;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@Override
public String toString() {
return "TestProperties{" +
"userName='" + userName + '\'' +
", email='" + email + '\'' +
", age=" + age +
", url='" + url + '\'' +
'}';
}
}
- properties文件中key除去prefix.后一定要和封装对象的field保持一致
- 在@ConfigurationProperties注解中配值需要自动封装的配置信息的前缀,@Component标识这个实体是一个组件,交由Spring容器管理,在使用的时候可以直接注入进来
2.3 编写Controller
TestController.java
import cn.sweetz.exercise.springbootdemo.property.TestProperties;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
@RestController
@RequestMapping("/test")
public class TestController {
@Resource
private TestProperties testProperties;
@GetMapping("/properties")
public String getTestProperties(){
return testProperties.toString();
}
}
3. 运行与测试
启动项目,等到项目启动好了后,输入地址:http://localhost:8060/test/properties
我们配置的一些信息已经自动帮我们封装到TestProperties实体中了,真的是很方便啊!