springboot為我們提供了application.properties文件,我們的key value值可以存放在此文件中,springboot會(huì)自動(dòng)加載application.properties文件和application*.yml文件但是很多情況下我們會(huì)自定義配置文件,由于自定義的配置文件spring并不能幫我們加載所以需要我們手動(dòng)讓它加載
1.application.propertis屬性的讀取
首先在application.properties文件中定義我們的key value值

然后定義屬性類Aliproperties
package com.example.demo.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix="com.ali")
public class Aliproperties {
private String address;
private String mail;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
}
使用

使用postman請(qǐng)求

成功獲取key value 值
二、自定義配置文件的讀取
由于自定義配置文件spring不能幫我們加載所以需要加上注解來讓spring加載
首先在resource目錄下新建config文件夾
新建properties文件并定義我們的key value值
test1=213
test2=222
定義TestProperties類 加上@PropertySource("classpath:config/test.properties")注解注入我們的文件
/**
*
*/
package com.example.jsp.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
/**
* @author ****
*
*/
@Configuration
@PropertySource("classpath:config/test.properties")
@ConfigurationProperties
public class TestProperties {
private String test1;
private String test2;
public String getTest1() {
return test1;
}
public void setTest1(String test1) {
this.test1 = test1;
}
public String getTest2() {
return test2;
}
public void setTest2(String test2) {
this.test2 = test2;
}
}
在啟動(dòng)類或者此類加上@EnableConfigurationProperties(TestProperties.class)注解
使用類似application.properties文件