標籤:設定檔 java 部落格 spring boot
Spring Boot預設的設定檔為application.properties,放在src/main/resources目錄下或者類路徑的/config目錄下,作為Spring Boot的全域設定檔,對一些預設的配置進行修改。
接下來使用例子展示Spring Boot設定檔的用法:
首先在src/main/resources下建立application.properties檔案,內容如下
author.name=微兒部落格author.sex=男
建立controller類
ackage com.springboot.properties;import org.springframework.beans.factory.annotation.Value;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;//不需要指定設定檔的位置,因為使用的預設的設定檔@RestControllerpublic class DemoController {@Value("${author.name}")//注入設定檔中的值private String name;@Value("${author.sex}")private String sex;@RequestMapping("/")public String index(){return name + ":" + sex;}}
建立入口類
package com.springboot.properties;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class App {public static void main(String[] args) {SpringApplication.run(App.class, args);}}
執行:
650) this.width=650;" src="http://www.weare.net.cn/EasyWeb/upload/image/20161219/1482132936140081094.png" title="微兒部落格" alt="微兒部落格" width="331" height="150" style="border:0px;vertical-align:middle;height:auto;" />
那麼如何使用其他的設定檔呢?
建立author.properties,內容如下:
person.name=weareperson.sex=man
修改DemoController為:
@RestController@PropertySource("classpath:author.properties")//指定設定檔public class DemoController {@Value("${person.name}")private String name;@Value("${person.sex}")private String sex;@RequestMapping("/")public String index(){return name + ":" + sex;}}
運行,
650) this.width=650;" src="http://www.weare.net.cn/EasyWeb/upload/image/20161219/1482134451232044044.png" title="微兒個人部落格" alt="微兒個人部落格" width="325" height="142" style="border:0px;vertical-align:middle;height:auto;" />
上例中屬性都是通過@Value逐個注入的,但是如果注入的屬性很多就會很麻煩,接下來使用@ConfigurationProperties將設定檔屬性和Bean的屬性關聯
建立Author類:
package com.springboot.properties;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.stereotype.Component;@Component//聲明這是一個Bean@ConfigurationProperties(prefix="author")//指定設定檔中的首碼public class Author {private String name;private String sex;public String getName() {return name;}public void setName(String name) {this.name = name;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}}
修改DemoController類:
@RestController@ConfigurationPropertiespublic class DemoController {@Autowiredprivate Author author;@RequestMapping("/")public String index(){return author.getName() + ":" + author.getSex();}}
運行App類,結果如:
650) this.width=650;" src="http://www.weare.net.cn/EasyWeb/upload/image/20161219/1482132936140081094.png" title="微兒部落格" alt="微兒部落格" width="331" height="150" style="border:0px;vertical-align:middle;height:auto;" />
更多資訊請訪問 微兒部落格
本文出自 “c67ed4” 部落格,請務必保留此出處http://c67ed4.blog.51cto.com/3429042/1884005
Spring Boot之設定檔application.properties