Spring Boot:配置文件中获取数据
具体方法:
- @value
- Environment
- @ConfigurationProperties
测试数据(下面数据格式适用于.yml 及 .yaml 配置文件):
name: abc
# 对象
person:
name: zhangsan
age: 20
# 对象行内写法
person0: {name: zhangsan,age: 20}
# 数组
Lists:
- beijing
- nanjing
# 数组行内写法
Lists0: [beijing,nanjing]
# 纯量
msg1: 'hello \n world ' # 不会识别转义字符,会原样输出
msg2: "hello \n world " # 会识别转义字符
一、@value 获取单个数据
获取单个数据
@Value("${name}")
private String name; //name被赋值为配置文件name的值
获得对象内数据
@Value("${person.name}")
private String name; //name被赋值为配置文件中Person对象中name的值
@Value("${person.age}")
private int age; //age被赋值为配置文件中Person对象中age的值
获取数组内数据
@Value("${Lists[0]}")
private String address0; //address0被赋值为Lists数组的第一个元素
@Value("${Lists[1]}")
private String address1; //address1被赋值为Lists数组的第二个元素
获取纯量数据
@Value("${msg1}")
private String msg1; //msg1被赋值为msg1的值,其中\n不被转义
@Value("${msg2}")
private String msg2; //msg2被赋值为msg1的值,其中\n被转义为换行符
二、Environment 获取所有
@Autowired
private Environment env ; //导入与Spring有关的包即可
String name = env.getProperty("person.name") //name被赋值为Person对象中的name
String list = env.getProperty("Lists[0]") //list被赋值为Lists数组中的第一个元素、
String msg = env.getProperty("msg1") //msg被赋值为msg1的值
三、@ConfigurationProperties
适用于将配置文件中的数据值赋值给一个类,其中类中具体元素的命名要和配置文件中数据命名要相同
创建person类 并添加注解@Component @ConfigurationProperties
@Component
@ConfigurationProperties(prefix = "person") //此时person类会获得配置文件中person对象中的name和age的值,如果使用上述数据,name=zhangsan,age=20
//@ConfigurationProperties //此时只会获得独立于对象等之外的元素值,如果使用上述测试数据的话,name=abc,age=0
Public class Person{
private String name;
private int age;
private String[] Lists;
//get、set、toString方法省略未写
}
在调用ConfigurationProperties方法时idea会出现Spring Boot Configuration Annotation Processor not found in classpath 的提示,此时我们需要在pom.xml文件的<dependencies> </dependencies>
中添加一下配置文件:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</ optional>
</dependency>
其余关于idea的快捷键:
iter: 快速生成 (如果使用之前就存在数组,则会自动添加数组,从而达到快速遍历数组)
for (Object o : ) { }
sout:快速生成System.out.println();