springBoot读取配置文件
pom.xml配置
在pom文件中我们加上配置文件加载器
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
读取类配置
package com.hanlin.springboot.bean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @author:hanlin.yuan
* @date:2019/05/30
*/
@Component
@ConfigurationProperties(prefix = "student")
public class Student {
private String name ;
private Integer age;
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;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
注意@ConfigurationProperties其中的prefix是只的读取配置文件中的对象名称
application.yml配置文件
student:
age: 18
name: 张三
注意:yml配置中,对象名称后面一定要有空格:列如:age:(空格)18
测试类
package com.hanlin.springboot;
import com.hanlin.springboot.bean.Student;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootDemo01ApplicationTests {
@Autowired
private Student student;
@Test
public void contextLoads() {
System.out.println(student);
}
}
测试结果: