springboot 設定檔讀取的兩種方式,以及使用到的註解解釋

來源:互聯網
上載者:User

標籤:依賴   not   ase   follow   指定   調用   ann   text   方法   

瞭解過spring-Boot這個技術的,應該知道Spring-Boot的核心設定檔application.properties,當然也可以通過註解自訂設定檔的資訊。

pom檔案

<dependencies>  <dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-web</artifactId>  </dependency>    <!-- 單元測試使用 -->    <dependency>      <groupId>org.springframework.boot</groupId>      <artifactId>spring-boot-starter-test</artifactId>    </dependency>    <dependency>      <groupId>junit</groupId>      <artifactId>junit</artifactId>      <scope>test</scope>    </dependency>    <dependency>      <groupId>org.springframework.boot</groupId>      <artifactId>spring-boot</artifactId>      <version>1.5.6.RELEASE</version>    </dependency>    <dependency>      <groupId>org.springframework.boot</groupId>      <artifactId>spring-boot-autoconfigure</artifactId>      <version>1.5.6.RELEASE</version>    </dependency>    <dependency>      <groupId>org.springframework.boot</groupId>      <artifactId>spring-boot-autoconfigure</artifactId>      <version>1.5.6.RELEASE</version>    </dependency>  </dependencies>

 

Spring-Boot讀取設定檔的方式:

一.讀取核心設定檔資訊application.properties的內容

     核心設定檔是指在resources根目錄下的application.properties或application.yml設定檔,讀取這兩個設定檔的方法有兩種,都比較簡單。

核心設定檔application.properties內容如下:

test.msg=Hello World SpringBoottest.name=testtest.password= 123test

方式一:使用@Value方式(常用)

package cn.ar.controller;import org.springframework.beans.factory.annotation.Value;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import java.util.Map;/** * Created with IntelliJ IDEA. * User: Jayden * Date: 2018/6/28 * Time: 9:57 */@RestController
//@PropertiesSource("classpath:application.properties")public class FirstController { @Value("${test.name}") private String name; @Value("${test.password}") private String password; @RequestMapping(value = "/test") public String say(){ return name+":application.propertoes裡面的name值"+"/t"+password+"密碼"; }}

注意:1.在@Value的${}中包含的是核心設定檔中的鍵名。在Controller類上加@RestController表示將此類中的所有視圖都以JSON方式顯示,類似於在視圖方法上加@ResponseBody。

[email protected]設定檔路徑設定,在類上添加註解,如果在預設路徑下可以不添加該註解 ,我這裡就在預設路徑下,所以上面沒用這個註解。
如果有多及目錄, 比如 classpath:config/my.properties指的是src/main/resources目錄下config目錄下的my.properties檔案.

3.多設定檔引用,若取兩個設定檔中有相同屬性名稱的值,則取值為最後一個設定檔中的值:

比如:@PropertySource({"classpath:config/my.properties","classpath:config/config.properties"})

訪問:http://localhost:8080/test時得到:"方式一:test:application.propertoes裡面的name值/t123test密碼"

 

方式二:使用Environment方式

package cn.ar.controller;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.core.env.Environment;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import java.util.Map;/** * Created with IntelliJ IDEA. * User: Jayden * Date: 2018/6/28 * Time: 9:57 */@RestControllerpublic class FirstController {   /* @Value("${test.name}")    private String  name;    @Value("${test.password}")    private String password;    @RequestMapping(value = "/test")    public String  say(){        return name+":application.propertoes裡面的name值"+"/t"+password+"密碼";    }*/   @Autowired   private Environment env;    @RequestMapping(value = "/test")    public String  say(){        return env.getProperty("test.name") + "      " +env.getProperty("test.password");    }}

注意:這種方式是依賴注入Evnironment來完成,在建立的成員變數private Environment env上加上@Autowired註解即可完成依賴注入,然後使用env.getProperty("鍵名")即可讀取出對應的值。

 

 

二.讀取自訂設定檔資訊,例如:detifalManager.properties

  1. 首先建立對象與設定檔映射關係
  2. 方法中使用自動注入方式,將對象注入,調用get方法擷取屬性值
  3. 注意:新版本的@ConfigurationProperties沒有了location屬性,使用@PropertySource來指定設定檔位置
  4. prefix=”user1”指的是設定檔中的首碼,如user1.name,在定義對象屬性名稱時為private String name;
  5. 讀取設定檔中的集合時,使用List來接收資料,但List必須先執行個體化,負責會報錯

為了不破壞核心檔案的原生態,但又需要有自訂的配置資訊存在,一般情況下會選擇自訂設定檔來放這些自訂資訊,這裡在resources目錄下建立設定檔detifalManager.properties

resources/detifalManager.properties內容如下:

user1.name=admin11111111user1.password=admin123qwqwquser1.age= 15user1.sex=男

建立管理配置的實體類:
package cn.ar.controller;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.context.annotation.PropertySource;import org.springframework.stereotype.Component;/** * Created with IntelliJ IDEA. * User: Jayden * Date: 2018/6/28 * Time: 10:24 */@Component//加上注釋@Component,可以直接在其他地方使用@Autowired來建立其實列對象@ConfigurationProperties(prefix = "user1")//設定設定檔的首碼@PropertySource("classpath:detifalManager.properties")//設定自訂檔案的路徑public class Manager {    private String name;    private String password;    private String sex;    private int age;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getPassword() {        return password;    }    public void setPassword(String password) {        this.password = password;    }    public String getSex() {        return sex;    }    public void setSex(String sex) {        this.sex = sex;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }}

注意:
    在@ConfigurationProperties注釋中有兩個屬性:
locations:指定設定檔的所在位置
prefix:指定設定檔中鍵名稱的首碼(我這裡設定檔中所有鍵名都是以user1.開頭)
    使用@Component是讓該類能夠在其他地方被依賴使用,即使用@Autowired注釋來建立執行個體。

建立測試Controller

package cn.ar.controller;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;/** * Created with IntelliJ IDEA. * User: Jayden * Date: 2018/6/28 * Time: 10:33 */@RestControllerpublic class SecondController {    @Autowired    Manager manager;    @RequestMapping("/test1")    public String say(){        return  "name"+ manager.getName() + "password" + manager.getPassword();    }}

注意:由於在manager類上加了注釋@Component,所以可以直接在這裡使用@Autowired來建立其執行個體對象。

訪問:http://localhost:8080/test1時得到:"name admin11111111 password  admin123qwqwq"

 

 

 

springboot 設定檔讀取的兩種方式,以及使用到的註解解釋

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.