SpringBoot可以使用两种配置文件,一种是application.properties;一种是application.yml。
application.properties 语法: key=value
application.yml 语法:key:(空格)value
配置文件的作用:修改SpringBoot自动配置的默认值,因为SpringBoot在底层都给我们配置好了。
YAML和XML
yaml配置:
server:
prot: 8080
xml配置:
<server>
<port>8081<port>
</server>
显然YAML更简洁一些。
YAML和Properties
YAML:
#对空格要求很高
#普通的key-value
name: SpringBoot
#对象
student:
name: xiaoming
age: 3
#数组
array:[cat,dog,pig]
Properties:
#只能存键值对
name=小明
给对象赋值
方式一:使用@Value注解
package com.example.demo.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
//将该类添加到Spring组件中
@Component
public class Person {
@Value("韩信")
private String name;
@Value("18")
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
测试代码:
package com.example.demo;
import com.example.demo.pojo.Person;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class DemoApplicationTests {
@Autowired
Person p ;
@Test
void contextLoads() {
System.out.println(p);
}
}
方式二:YAML配置需要@ConfigurationProperties注解
@ConfigurationProperties注解作用:将配置文件中的每一个属性的值,映射到这个组件中;告诉SpringBoot将本类中的所有属性和配置文件相关的配置进行绑定。
YAML文件配置:
person:
name: 李白
age: 20
package com.example.demo.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
//将该类添加到Spring组件中
@Component
@ConfigurationProperties(prefix = "person") //该注解代表是一个配置
public class Person {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
测试部分同上。