天天看點

Spring Boot 屬性配置和使用

Spring Boot 屬性配置和使用

Spring Boot 允許通過外部配置讓你在不同的環境使用同一應用程式的代碼,簡單說就是可以通過配置檔案來注入屬性或者修改預設的配置。

Spring Boot 系列

  1. ​​Spring Boot 入門​​
  2. ​​Spring Boot 屬性配置和使用​​
  3. ​​Spring Boot 內建MyBatis​​
  4. ​​Spring Boot 靜态資源處理​​
  5. ​​Spring Boot - 配置排序依賴技巧​​
  6. ​​Spring Boot - DevTools 介紹​​

Spring Boot 支援多種外部配置方式

這些方式優先級如下:

  1. 指令行參數
  2. 來自​

    ​java:comp/env​

    ​的JNDI屬性
  3. Java系統屬性(​

    ​System.getProperties()​

    ​)
  4. 作業系統環境變量
  5. ​RandomValuePropertySource​

    ​​配置的​

    ​random.*​

    ​屬性值
  6. ​jar​

    ​​包外部的​

    ​application-{profile}.properties​

    ​​或​

    ​application.yml​

    ​​(帶​

    ​spring.profile​

    ​)配置檔案
  7. ​jar​

    ​​包内部的​

    ​application-{profile}.properties​

    ​​或​

    ​application.yml​

    ​​(帶​

    ​spring.profile​

    ​)配置檔案
  8. ​jar​

    ​​包外部的​

    ​application.properties​

    ​​或​

    ​application.yml​

    ​​(不帶​

    ​spring.profile​

    ​)配置檔案
  9. ​jar​

    ​​包内部的​

    ​application.properties​

    ​​或​

    ​application.yml​

    ​​(不帶​

    ​spring.profile​

    ​)配置檔案
  10. ​@Configuration​

    ​​注解類上的​

    ​@PropertySource​

  11. 通過​

    ​SpringApplication.setDefaultProperties​

    ​指定的預設屬性

指令行參數

通過​

​java -jar app.jar --name="Spring" --server.port=9090​

​方式來傳遞參數。

參數用​

​--xxx=xxx​

​的形式傳遞。

可以使用的參數可以是我們自己定義的,也可以是Spring Boot中預設的參數。

很多人可能會關心如web端口如何配置這樣的問題,這些都是Spring Boot中提供的參數,部分可用參數如下:

# LOGGING
logging.path=/var/logs
logging.file=myapp.log
logging.config= # location of config file (default classpath:logback.xml for logback)
logging.level.*= # levels for loggers, e.g. "logging.level.org.springframework=DEBUG" (TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF)

# EMBEDDED SERVER CONFIGURATION (ServerProperties)
server.port=8080
server.address= # bind to a specific NIC
server.session-timeout= # session timeout in seconds
server.context-parameters.*= # Servlet context init parameters, e.g. server.context-parameters.a=alpha
server.context-path= # the context path, defaults to '/'
server.servlet-path= # the servlet path, defaults to '/'      

更多常見的應用屬性請浏覽​​這裡​​

注意:指令行參數在​

​app.jar​

​的後面!

可以通過​

​SpringApplication.setAddCommandLineProperties(false)​

​禁用指令行配置。

Java系統屬性

注意Java系統屬性位置​

​java -Dname="isea533" -jar app.jar​

​,可以配置的屬性都是一樣的,優先級不同。

例如​

​java -Dname="isea533" -jar app.jar --name="Spring!"​

​​中​

​name​

​​值為​

​Spring!​

作業系統環境變量

配置過JAVA_HOME的應該都了解這一個。

這裡需要注意的地方,有些OS可以不支援使用​

​.​

​​這種名字,如​

​server.port​

​​,這種情況可以使用​

​SERVER_PORT​

​來配置。

具體名字如何比對,看本文後面。

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]}      

​random.int*​

​​支援​

​value​

​​參數和​

​,max​

​​參數,當提供​

​max​

​​參數的時候,​

​value​

​就是最小值。

應用配置檔案(.properties或.yml)

在配置檔案中直接寫:

name=Isea533
server.port=8080      

​.yml​

​格式的配置檔案如:

name: Isea533
server:
    port: 8080      

當有字首的情況下,使用​

​.yml​

​​格式的配置檔案更簡單。關于​

​.yml​

​​配置檔案用法請看​​這裡​​

注意:使用​

​.yml​

​​時,屬性名的值和冒号中間必須有空格,如​

​name: Isea533​

​​正确,​

​name:Isea533​

​就是錯的。

屬性配置檔案的位置

spring會從classpath下的​

​/config​

​​目錄或者classpath的根目錄查找​

​application.properties​

​​或​

​application.yml​

​。

​/config​

​​優先于​

​classpath根目錄​

@PropertySource

這個注解可以指定具體的屬性配置檔案,優先級比較低。

SpringApplication.setDefaultProperties

例如:

SpringApplication application = new SpringApplication(Application.class);
Map<String, Object> defaultMap = new HashMap<String, Object>();
defaultMap.put("name", "Isea-Blog");
//還可以是Properties對象      

應用(使用)屬性

@Value(“${xxx}”)

這種方式是最簡單的,通過​

​@Value​

​注解可以将屬性值注入進來。

@ConfigurationProperties

Spring Boot 可以友善的将屬性注入到一個配置對象中。例如:

my.name=Isea533
my.port=8080
my.servers[0]=dev.bar.com
my.servers[1]=foo.bar.com      

對應對象:

@ConfigurationProperties(prefix="my")
public class Config
    private String name;
    private Integer port;
    private List<String> servers = new ArrayList<String>();

    public String geName(){
        return this.name;
    }

    public Integer gePort(){
        return this.port;
    }
    public List<String> getServers() {
        return this.servers;
    }
}      

Spring Boot 會自動将​

​prefix="my"​

​​字首為​

​my​

​的屬性注入進來。

Spring Boot 會自動轉換類型,當使用​

​List​

​​的時候需要注意在配置中對​

​List​

​進行初始化!

Spring Boot 還支援嵌套屬性注入,例如:

name=isea533
jdbc.username=root
jdbc.password=root
...      

對應的配置類:

@ConfigurationProperties
public class Config
    private String name;
    private Jdbc jdbc;
    class Jdbc {
        private String username;
        private String password;
        //getter...
    }

    public Integer gePort(){
        return this.port;
    }
    public Jdbc getJdbc() {
        return this.jdbc;
    }
}      

​jdbc​

​​開頭的屬性都會注入到​

​Jdbc​

​對象中。

在@Bean方法上使用@ConfigurationProperties

例如:

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

Spring Boot 會将​

​foo​

​​開頭的屬性按照名字比對注入到​

​FooComponent​

​對象中。

屬性占位符

例如:

app.name=MyApp
app.description=${app.name} is a Spring Boot application      

可以在配置檔案中引用前面配置過的屬性(優先級前面配置過的這裡都能用)。

通過如​

​${app.name:預設名稱}​

​方法還可以設定預設值,當找不到引用的屬性時,會使用預設的屬性。

由于​

​${}​

​​方式會被Maven處理。如果你pom繼承的​

​spring-boot-starter-parent​

​​,Spring Boot 已經将​

​maven-resources-plugins​

​​預設的​

​${}​

​​方式改為了​

​@ @​

​​方式,例如​

​@name@​

​。

如果你是引入的Spring Boot,你可以修改使用​​其他的分隔符​​

通過屬性占位符還能縮短指令參數

例如修改web預設端口需要使用​

​--server.port=9090​

​方式,如果在配置中寫上:

server.port=${port:8080}      

那麼就可以使用更短的​

​--port=9090​

​​,當不提供該參數的時候使用預設值​

​8080​

​。

屬性名比對規則

例如有如下配置對象:

@Component
@ConfigurationProperties(prefix="person")
public class ConnectionSettings

    private      

​firstName​

​可以使用的屬性名如下:

  1. ​person.firstName​

    ​,标準的駝峰式命名
  2. ​person.first-name​

    ​​,虛線(​

    ​-​

    ​​)分割方式,推薦在​

    ​.properties​

    ​​和​

    ​.yml​

    ​配置檔案中使用
  3. ​PERSON_FIRST_NAME​

    ​,大寫下劃線形式,建議在系統環境變量中使用

屬性驗證

可以使用​

​JSR-303​

​注解進行驗證,例如:

@Component
@ConfigurationProperties(prefix="connection")
public class ConnectionSettings

    @NotNull
    private InetAddress remoteAddress;

    // ... getters and setters      

最後

繼續閱讀