yaml方式注入配置文件
1、在springboot项目中的resources目录下新建一个文件 application.yml
2、编写一个实体类 Dog;
import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Component @ConfigurationProperties(prefix = "dog") public class Dog { private String firstName; private Integer age; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Dog(String firstName, Integer age) { this.firstName = firstName; this.age = age; } public Dog() { } @Override public String toString() { return "Dog{" + "firstName='" + firstName + '\'' + ", age=" + age + '}'; } }
3、我们在编写一个复杂一点的实体类:Person 类
import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; import org.springframework.validation.annotation.Validated; import javax.validation.constraints.Email; import java.util.Date; import java.util.List; import java.util.Map; @Component @ConfigurationProperties(prefix = "person") @Validated //数据校验 //加载指定的配置文件 //@PropertySource(value = "classpath:xiaobai.properties") public class Person { //spring的EL表达式 //@Value("${name}") @Email(message = "email geshi error") private String name; private Integer age; private Boolean happy; private Date birth; private Mapmaps; private List
4、我们来使用yaml配置的方式进行注入,大家写的时候注意区别和优势,我们编写一个yaml配置
person:
name: xiaobai
age: 3
happy: true
birth: 2001/02/03
maps: {k1: v1,k2: v2}
lists:
- code
- music
- girl
dog:
name: wangcai
age: 3
dog:
first-name: xiaohuang
age: 3
5、IDEA 提示,springboot配置注解处理器没有找到,让我们看文档,我们可以查看文档,找到一个依 赖!
<dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-configuration-processorartifactId> <optional>trueoptional> dependency>
6、确认以上配置都OK之后,我们去测试类中测试一下:
import com.bai.pojo.Dog; import com.bai.pojo.Person; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class Springboot03ConfigApplicationTests { @Autowired private Dog dog; @Test void contextLoads() { System.out.println(dog); } }