1. 程式人生 > >SpringBoot 二 配置檔案application.properties/yml

SpringBoot 二 配置檔案application.properties/yml

src/main/java/resources目錄下

1.自定義屬性

提供自定義屬性的支援,這樣我們就可以把一些常量配置在這裡:

然後直接在要使用的地方通過註解@Value(value=”${config.name}”)就可以繫結到你想要的屬性上面

package com.example.demo.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
public class HelloController {

@Value("${name}")
private String name;
@Value("${age}")
private int age;
@Value("${mix}")
private String mix;

@RequestMapping("/hello")
public String hello(Model model){

    model.addAttribute("name","thymeleaf");
    return "hello" ;
}


    @RequestMapping("/hello2")
    @ResponseBody
    public String hello2(){
        return mix;
    }

}

有時候屬性太多了,一個個繫結到屬性欄位上太累,官方提倡繫結一個物件的bean,這裡我們建一個ConfigBean.java類,頂部需要使用註解@ConfigurationProperties(prefix = “cxy”)來指明使用哪個

package com.example.demo.bean;

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "demo")
public class ConfigBean {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

坑一:

出現spring boot Configuration Annotation Proessor not found in classpath的提示是在用了@ConfigurationProperties這個註解時,所以問題出現在ConfigurationProperties註解。

官方解決方案,Maven引入依賴

<dependency>
			<groupId> org.springframework.boot </groupId>
			<artifactId> spring-boot-configuration-processor </artifactId>
			<optional> true </optional>
		</dependency>

這裡配置完還需要在spring Boot入口類加上@EnableConfigurationProperties並指明要載入哪個bean

最後在Controller中引入ConfigBean使用即可,如下:

package com.example.demo.controller;

import com.example.demo.bean.ConfigBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
public class HelloController {

    @Autowired
    ConfigBean configBean;

    @RequestMapping("/hello2")
    @ResponseBody
    public String hello2(){
        return configBean.getMix();
    }

}

 也可以用@RestController註解

其等價於@[email protected]的結合,使用這個註解的類裡面的方法都以json格式輸出。

 

2.使用自定義配置檔案,同時用兩個配置檔案?

有時候我們不希望把所有配置都放在application.properties裡面,這時候我們可以另外定義一個,這裡我明取名為test.yml,路徑跟也放在src/main/resources下面。

新建一個bean類,如下:

package com.example.demo.bean;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration
@ConfigurationProperties(prefix = "demo2")
@PropertySource("classpath:test.yml")
public class ConfigTestBean {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

新增@Configuration和@PropertySource(“classpath:test.yml”)後才可以才可以讀取。

在主入口新增

Controller就可以注入並同時使用了 。

package com.example.demo.controller;

import com.example.demo.bean.ConfigBean;
import com.example.demo.bean.ConfigTestBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
public class HelloController {


@RequestMapping("/hello")
public String hello(Model model){

    model.addAttribute("name","thymeleaf");
    return "hello" ;
}
    @Autowired
    ConfigBean configBean;
    @Autowired
    ConfigTestBean configTestBean;

    @RequestMapping("/hello2")
    @ResponseBody
    public String hello2(){
        return configBean.getMix()+"......."+configTestBean.getName();
    }

}

3.隨機值配置

配置檔案中${random} 可以用來生成各種不同型別的隨機值,從而簡化了程式碼生成的麻煩,例如 生成 int 值、long 值或者 string 字串。

4.外部配置-命令列引數配置(詳情參考

打成jar包的程式可以直接通過下面命令執行:

1
java -jar xx.jar

 

可以以下命令修改tomcat埠號:

1
java -jar xx.jar --server.port=9090

 

可以看出,命令列中連續的兩個減號--就是對application.properties中的屬性值進行賦值的標識。
所以java -jar xx.jar --server.port=9090等價於在application.properties中新增屬性server.port=9090
如果你怕命令列有風險,可以使用SpringApplication.setAddCommandLineProperties(false)禁用它。

5.屬性源

實際上,Spring Boot應用程式有多種設定途徑,Spring Boot能從多重屬性源獲得屬性,包括如下幾種:

  • 根目錄下的開發工具全域性設定屬性(當開發工具啟用時為~/.spring-boot-devtools.properties)。
  • 測試中的@TestPropertySource註解。
  • 測試中的@SpringBootTest#properties註解特性。
  • 命令列引數
  • SPRING_APPLICATION_JSON中的屬性(環境變數或系統屬性中的內聯JSON嵌入)。
  • ServletConfig初始化引數。
  • ServletContext初始化引數。
  • java:comp/env裡的JNDI屬性
  • JVM系統屬性
  • 作業系統環境變數
  • 隨機生成的帶random.* 字首的屬性(在設定其他屬性時,可以應用他們,比如${random.long})
  • 應用程式以外的application.properties或者appliaction.yml檔案
  • 打包在應用程式內的application.properties或者appliaction.yml檔案
  • 通過@PropertySource標註的屬性源
  • 預設屬性(通過SpringApplication.setDefaultProperties指定).

這裡列表按組優先順序排序,也就是說,任何在高優先順序屬性源裡設定的屬性都會覆蓋低優先順序的相同屬性,列如我們上面提到的命令列屬性就覆蓋了application.properties的屬性。

6.配置檔案的優先順序

application.yml和appilcation.properties可以放在以下4個位置

  • 外接,在相對於應用程式執行目錄的/congfig子目錄裡。
  • 外接,在應用程式執行的目錄裡
  • 內建,在config包內
  • 內建,在Classpath根目錄

所以,這種情況下,src/main/resources/config下application.properties覆蓋src/main/resources下application.properties中相同的屬性,如圖:

此外,如果你在相同優先順序位置同時有application.properties和application.yml,那麼application.yml裡面的屬性就會覆蓋application.properties裡的屬性。這個不用深究,一般用官方推薦的yml檔案。

7.Profile-多環境配置

當應用程式需要部署到不同執行環境時,一些配置細節通常會有所不同,最簡單的比如日誌,生產日誌會將日誌級別設定為WARN或更高級別,並將日誌寫入日誌檔案,而開發的時候需要日誌級別為DEBUG,日誌輸出到控制檯即可。
如果按照以前的做法,就是每次釋出的時候替換掉配置檔案,這樣太麻煩了,Spring Boot的Profile就給我們提供瞭解決方案,命令帶上引數就搞定。

這裡我們來模擬一下,只是簡單的修改埠來測試
在Spring Boot中多環境配置檔名需要滿足application-{profile}.properties的格式,其中{profile}對應你的環境標識,比如:

  • application-dev.properties:開發環境
  • application-prod.properties:生產環境

想要使用對應的環境,只需要在application.properties中使用spring.profiles.active屬性來設定,值對應上面提到的{profile},這裡就是指dev、prod這2個。spring.profiles.include進行疊加也是可以的

spring.profiles.active: xx
spring.profiles.include: xx,yy

參考;常用屬性彙總