spring boot 設定檔application

來源:互聯網
上載者:User

標籤:xxx   作用   配置環境   生產環境   style   顯示   參考   jar包   地方   

情境:在項目部署的過程中,對於spring boot的設定檔一直不很瞭解,直到項目出現一個莫名其妙的問題——工程classes中的設定檔被覆蓋,程式啟動總是報錯!

 

1  設定檔的優先順序

application.properties大家都不陌生,我們在開發的時候,經常使用它來配置一些可以手動修改而且不用編譯的變數,這樣的作用在於,打成war包或者jar用於生產環境時,我們可以手動修改環境變數而不用再重新編譯。

spring boo預設已經配置了很多環境變數,例如,tomcat的預設連接埠是8080,項目的contextpath是“/”等等,可以在這裡看spring boot預設的配置資訊http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-external-config

1.1 配置項讀取順序
  1. 命令列參數
  2. 通過 SPRING_APPLICATION_JSON 設定的值
  3. JNDI attributes from java:comp/env
  4. Java 系統屬性(System.getProperties())
  5. 作業系統環境變數
  6. A RandomValuePropertySource that only has properties in random.*.
  7. 項目 Jar 外的Profile 相關的設定檔(application-{profile}.properties)
  8. Jar 內的Profile 相關的設定檔(application-{profile}.properties)
  9. 項目 Jar 外的設定檔(application.properties)
  10. Jar 內的設定檔(application.properties)
  11. @PropertySource annotations on your @Configuration classes.
  12. 預設屬性 (SpringApplication.setDefaultProperties)
1.2  application.properties 尋找位置

除了在application.properties配置參數,還有多種方式可以設定參數。Spring Boot 按照下面的順序尋找配置項:

spring boot允許你自訂一個application.properties檔案,然後放在以下的地方,來重寫spring boot的環境變數或者定義你自己環境變數

Spring Boot 預設從4個位置尋找application.properties檔案。

  1. 目前的目錄下的/config目錄
  2. 目前的目錄
  3. 類路徑下的/config目錄
  4. 類路徑根目錄

說明:
目前的目錄指的是運行Jar檔案時的目錄,不一定是jar檔案所在目錄,所有上面前2項是Jar包外目錄。

如果同時在四個地方都有設定檔,設定檔的優先順序是從1到4。

  • 目前的目錄,目前不知道如何確定,但是spring在啟動的時候會顯示目前的目錄:

根據xxxApplicationStarter可以定位到目前的目錄。然後根據需要配置設定檔。

 

  • 類路徑:

也就是classes目錄。

 1.3 讀取和設定設定檔屬性

參考文章http://www.nathanyan.com/2016/01/25/Spring-Boot-04-%E9%85%8D%E7%BD%AE%E7%9B%B8%E5%85%B3/

 使用設定檔之後,spring boo啟動時,會自動把配置資訊讀取到spring容器中,並覆蓋spring boot的預設配置,那麼,我們怎麼來讀取和設定這些配置資訊呢

1.通過命令列來重寫和配置環境變數,優先順序最高,例如可以通過下面的命令來重寫spring boot 內嵌tomcat的服務連接埠,注意“=”倆邊不要有空格

java -jar demo.jar --server.port=9000

如果想要設定多個變數怎麼辦,可以已json的格式字串來設定

java -jar demo.jar --spring.application.json=‘{"foo":"bar"}‘

 

 

2.通過@value註解來讀取

@RestController@RequestMapping("/task")public class TaskController {@Value("${connection.remoteAddress}") private String address;@RequestMapping(value = {"/",""})public String hellTask(@Value("${connection.username}")String name){    return "hello task !!";}}

 

 

3.通過Environment介面來擷取,只需要把介面注進去即可

@RestController@RequestMapping("/task")public class TaskController {@Autowired Environment ev ;@Value("${connection.remoteAddress}") private String address;@RequestMapping(value = {"/",""})public String hellTask(@Value("${connection.username}")String name){    String password = ev.getProperty("connection.password");    return "hello task !!";}}

 

 

4.可以自訂一個工具類,來擷取,這種方式關鍵在於讀取設定檔資訊,適合自訂的配置資訊,spring 容器預設的配置資訊會讀不到

@Componentpublic class SystemConfig {    private static Properties props ;    public SystemConfig(){        try {            Resource resource = new ClassPathResource("/application.properties");//            props = PropertiesLoaderUtils.loadProperties(resource);        } catch (IOException e) {            e.printStackTrace();        }    }    /**     * 擷取屬性     * @param key     * @return     */    public static String getProperty(String key){        return props == null ? null :  props.getProperty(key);    }    /**     * 擷取屬性     * @param key 屬性key     * @param defaultValue 屬性value     * @return     */    public static String getProperty(String key,String defaultValue){         return props == null ? null : props.getProperty(key, defaultValue);    }    /**     * 擷取properyies屬性     * @return     */    public static Properties getProperties(){        return props;    }}//用的話,就直接這樣子String value = SystemConfig.getProperty("key");

 

 

5.可以利用${…}在application.properties引用變數

myapp.name=springmyapp.desc=${myapp.name} nice

 

6.可以在application.properties配置隨機變數,利用的是RandomValuePropertySource類

my.secret=${random.value}my.number=${random.int}my.bignumber=${random.long}my.number.less.than.ten=${random.int(10)}my.number.in.range=${random.int[1024,65536]}

 

 

7.綁定屬性值到Bean

YAML檔案

properties檔案在面對有層次關係的資料時,就有點不合適。YAML 支援一種類似JSON的格式,可以表現具有層次的資料。詳細說明看這裡.
YAML的內容會轉換為properties格式,如下:

environments:    dev:        url: http://dev.bar.com        name: Developer Setup    prod:        url: http://foo.bar.com        name: My Cool Appmy:   servers:       - dev.bar.com       - foo.bar.com

 

 

environments.dev.url=http://dev.bar.comenvironments.dev.name=Developer Setupenvironments.prod.url=http://foo.bar.comenvironments.prod.name=My Cool Appmy.servers[0]=dev.bar.commy.servers[1]=foo.bar.com

可以用@Value("${environments.dev.url}")注入.

 

YAML的一個特性就是可以把多個檔案的配置項,合并到一個檔案裡。用---分隔。

server:    address: 192.168.1.100---spring:    profiles: developmentserver:    address: 127.0.0.1---spring:    profiles: productionserver:    address: 192.168.1.120

再結合spring.profiles可以指定Profile下使用哪個配置項.

Spring Boot 也支援Profile特性,Profile相關的設定檔命名為:application-{profile}.properties,可以用spring.profiles.active啟用Profile:

java -jar target/demo-0.0.1-SNAPSHOT.jar --spring.profiles.active=test

 

 

雖然可以通過@Value("${property}")注入屬性值,如果有多項需要注入,就有點麻煩了。@ConfigurationProperties可以直接把多個屬性值綁定到Bean上。

設定檔:

# application.ymlconnection:    username: admin    remoteAddress: 192.168.1.1

 

使用:

@Component@ConfigurationProperties(prefix="connection")public class ConnectionSettings {    private String username;    private InetAddress remoteAddress;    // ... getters and setters}

 

 

也可以在建立Bean時注入:

@ConfigurationProperties(prefix = "foo")@Beanpublic FooComponent fooComponent() {    ...}

 

 

 

3

spring boot 設定檔application

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.