Spring Boot有兩中類型的配置文件:.properties和.yml。Spring Boot默認的全局配置文件名爲application.properties或者application.yml(spring官方推薦使用的格式是.yml格式,目前官網都是實例都是使用yml格式進行配置講解的),應用啓動時會自動加載此文件,無需手動引入。web
我自定義一個配置文件my.propertiesspring
student.name = ZhangSan student.age = ${random.int[1,30]} student.parents[0] = ZhangMing student.parents[1] = XiaoHua
建立一個Bean,用於自動讀取配置文件的內容(注:需保證與配置文件的字段一致)springboot
import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; import java.util.List; /** * Created by Administrator on 2018/9/28. */ @Component @PropertySource(value = "classpath:/my.properties", encoding="utf-8") //設置系統加載自定義的配置文件,並指定配置文件編碼格式 @ConfigurationProperties(prefix = "student") @Data public class Student { private String name; private int age; private List<String> parents; }
import com.jc.testConf.Student; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * Created by Administrator on 2018/6/26. */ @RestController public class HelloController { @Autowired Student student; @RequestMapping("/testConf") private String getStudent(){ return student.toString(); } }
測試,果真可以獲取到配置文件的數據
因此,之後,就可經過配置對象來獲取相關的配置便可。app
import com.jc.testConf.Student; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * Created by Administrator on 2018/6/26. */ @RestController public class HelloController { @Value(value = "${student.name}") String name; @RequestMapping("/studentName") private String studentName(){ return name; } }
測試能夠獲取
dom
在學習配置中,設計到其餘的知識點,全部在文章末尾補充下。學習
有三種使用方式:測試
https://blog.lqdev.cn/2018/07/14/springboot/chapter-third/
http://blog.51cto.com/4247649/2118348編碼