我的springboot之路(2)----springboot自定義配置詳解
阿新 • • 發佈:2018-12-08
一、前言
我的springboot之路(1)介紹了springboot的誕生背景以及優點等,我們知道springboot簡化了程式設計配置,它體現出了一種 約定優於配置,也稱作按約定程式設計,是一種軟體設計正規化,旨在減少軟體開發人員需做決定的數量,獲得簡單的好處,而又不失靈活性。 一般情況下預設的配置足夠滿足日常開發所需,但在某些情況下,我們可能需要用到自定義屬性配置、自定義檔案配置等一系列功能。那麼,這些自定義配置需要怎麼做呢?
1、自定義屬性配置
(1)在src-resource中找到application.properties檔案,內容如下:
test.example= 1
test.name=defineProperties
(2)建立Example1檔案,
package com.example.demo;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @author Felix
* @date 2018/12/8 13:41
*/
@Component
@ConfigurationProperties(prefix = "test" )
public class Example1 {
private int example;
private String name;
public int getExample() {
return example;
}
public void setExample(int example) {
this.example = example;
}
public String getName() {
return name;
}
public void setName (String name) {
this.name = name;
}
}
(3)建立PropertiesController檔案
@RequestMapping("/properties")
@RestController
public class PropertiesController {
//private static final Logger log = LoggerFactory.getLogger(PropertiesController.class);
private Example1 example1;
private Example2 example2;
@Autowired
public PropertiesController(Example1 example1){
this.example1 = example1;
}
@GetMapping("/1")
public Example1 getExample1(){
return example1;
}
}
(4)執行專案的Application檔案,然後開啟瀏覽器,輸入:http://localhost:8080/properties/1 ,回車即可。
2、自定義檔案配置
(1)在resource下建立testfile.properties檔案,內容如下:
testfile.example=2
testfile.name=defineFile
(2)建立Example2檔案
package com.example.demo;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
/**
* @author Felix
* @date 2018/12/8 13:43
*/
@Component
@PropertySource("classpath:testfile.properties")
@ConfigurationProperties(prefix = "testfile")
public class Example2 {
private int example;
private String name;
public int getExample() {
return example;
}
public void setExample(int example) {
this.example = example;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
(3)修改PropertiesController的建構函式,並新增getExample2()方法
private Example2 example2;
@Autowired
public PropertiesController(Example1 example1,Example2 example2){
this.example1 = example1;
this.example2 = example2;
}
@GetMapping("/2")
public Example2 getExample2(){
return example2;
}
(4)執行專案的Application檔案,然後開啟瀏覽器,輸入:http://localhost:8080/properties/2 ,回車即可。