springBoot讀取配置檔案
- pom.xml配置
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);
}
}
測試結果:
