在SpringBoot中,通常会使用注释@ConfigurationProperties(prefix = "xxx")来配置文件,但是在SpringBoot中,还可以使用Value注释来获取对应的属性:
如创建一个yaml文件:
person:
address: '优快云'
age: 19
friends:
-f1
-f2
-f3
name: "name1"
school: "TWTDX"
在创建person类:
@Component
@Validated
public class Person {
@Value("${person.name}")//通过${xxx.xx}找到对应的属性
String name;
@Value("${person.age}")
Integer age;
@Value("${person.friends}")
List<String> friends;
@Value("${person.address}")
String address;
@Value("${person.school}")
String school;
@Override
public String toString() {
return "person{" +
"name='" + name + '\'' +
", age=" + age +
", friends=" + friends +
", address='" + address + '\'' +
", school='" + school + '\'' +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public List<String> getFriends() {
return friends;
}
public void setFriends(List<String> friends) {
this.friends = friends;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getSchool() {
return school;
}
public void setSchool(String school) {
this.school = school;
}
}
编写Test
@RunWith(SpringRunner.class)
@SpringBootTest
class Demo12ApplicationTests {
@Autowired
Person person;
@Test
void contextLoads() {
System.out.print(person);
}
}
运行结果如下
与@ConfigurationProperties(prefix = "xxx")相比,使用Value更为麻烦,需要一个个为属性配置,且其不支持松散绑定,即Value必须名字完全一致,而@ConfigurationProperties(prefix = "xxx")中可以存在一些大小写,符号的不同,但内容不能出现大的差距,如
YAML改为
person:
address: '优快云'
Age: 19
fri-ends:
-f1
-f2
-f3
names: "name1"
school-high: "TWTDX"
使用@ConfigurationProperties(prefix = "xxx")输出结果如下:
而value则会报错:
而SpringBoot 启动会扫描以下位置的application.properties或者application.yml文件作为Spring Boot的默认配置文件
–file:./config/
–file:./
–classpath:/config/
–classpath:/
优先级由高到底,全部加载主配置文件,高优先级的配置会覆盖低优先级的配置,同时互补配置;也可以使用@PropertySource,加载指定的配置文件:、
编写person.properties
person.address=where
person.name=who
person.school=what
person.age=111
指定为person.properties:
但是这种写法下,其优先还是会读取默认的properties内的内容,所以要区分名字;如
默认的application.properties
person.address=aaa
person.name="name \n 1"
而自定义的person
person.address=where
person.name=who
person.school=what
person.age=111
person.friends=f1,f2,f3
其运行结果为
默认情况下,@PropertySource不会加载YAML文件。需要自己去手动实现这个功能。
而在SpringBoot中,其没有Spring的配置文件,即便我们自己编写配置文件,也不能被自动识别;所以想让Spring的配置文件生效,将其加载到SpringBoot中,我们需要使用@ImportResource标注在一个配置类上,使其生效,如下代码: