核心配置文件是指在resources根目錄下的application.properties
或application.yml
配置文件,讀取這兩個配置文件的方法有兩種,都比較簡單。php
核心配置文件application.properties
內容以下:java
server.port=9090 test.msg=Hello World Springboot!
@Value
方式(經常使用):@RestController public class WebController { @Value("${test.msg}") private String msg; @RequestMapping(value = "index", method = RequestMethod.GET) public String index() { return "The Way 1 : " +msg; } }
注意:在@Value
的${}中包含的是核心配置文件中的鍵名。在Controller類上加@RestController
表示將此類中的全部視圖都以JSON方式顯示,相似於在視圖方法上加@ResponseBody
。git
訪問:http://localhost:9090/index 時將獲得The Way 1 : Hello World Springboot!
github
Environment
方式@RestController public class WebController { @Autowired private Environment env; @RequestMapping(value = "index2", method = RequestMethod.GET) public String index2() { return "The Way 2 : " + env.getProperty("test.msg"); } }
注意:這種方式是依賴注入Evnironment
來完成,在建立的成員變量private Environment env
上加上@Autowired
註解便可完成依賴注入,而後使用env.getProperty("鍵名")
便可讀取出對應的值。web
訪問:http://localhost:9090/index2 時將獲得The Way 2 : Hello World Springboot!
bash
爲了避免破壞核心文件的原生態,但又須要有自定義的配置信息存在,通常狀況下會選擇自定義配置文件來放這些自定義信息,這裏在resources/config
目錄下建立配置文件my-web.properties
app
resources/config/my-web.properties
內容以下:ide
web.name=zslin web.version=V 1.0 web.author=393156105@qq.com
@ConfigurationProperties(locations = "classpath:config/my-web.properties", prefix = "web") @Component public class MyWebConfig { private String name; private String version; private String author; public String getAuthor() { return author; } public String getName() { return name; } public String getVersion() { return version; } public void setAuthor(String author) { this.author = author; } public void setName(String name) { this.name = name; } public void setVersion(String version) { this.version = version; } }
注意:測試
在@ConfigurationProperties
註釋中有兩個屬性:this
locations
:指定配置文件的所在位置prefix
:指定配置文件中鍵名稱的前綴(我這裏配置文件中全部鍵名都是以web.
開頭) 使用@Component
是讓該類可以在其餘地方被依賴使用,即便用@Autowired
註釋來建立實例。
@RestController @RequestMapping(value = "config") public class ConfigController { @Autowired private MyWebConfig myWebConfig; @RequestMapping(value = "index", method = RequestMethod.GET) public String index() { return "webName: "+myWebConfig.getName()+", webVersion: "+ myWebConfig.getVersion()+", webAuthor: "+myWebConfig.getAuthor(); } }
注意:因爲在MyWebConfig類上加了註釋@Component
,因此能夠直接在這裏使用@Autowired
來建立其實例對象。
訪問:http://localhost:9090/config/index 時將獲得webName: zslin, webVersion: V 1.0, webAuthor: 393156105@qq.com