Spring Boot系列--屬性配置

Spring Boot系列--屬性配置

目錄

1、命令行參數

2、配置文件

2.1、@Value註解直接注入

2.2、通過@ConfigurationProperties綁定到結構化對象


版本:2.0.8.RELEASE

本文源碼 https://github.com/shuiyuebingdian/springboot-example-parent/tree/master/ExternalizedConfiguration

Spring Boot允許外化(externalize)你的配置,這樣你能夠在不同的環境下使用相同的代碼。你可以使用properties文件,YAML文件,環境變量和命令行參數來外化配置。使用@Value註解,可以直接將屬性值注入到你的beans中,或者通過Spring的Environment抽象來訪問或通過@ConfigurationProperties綁定到結構化對象。spring boot支持多種外部配置方式,常用以下幾種:

  1. 命令行參數
  2. 配置文件

更多使用方式請瀏覽這裏

1、命令行參數

通過java -jar app.jar --name="Spring" --server.port=9090方式來傳遞參數。

參數用--xxx=xxx的形式傳遞。

可以使用的參數可以是我們自己定義的,也可以是Spring Boot中默認的參數

2、配置文件

springboot會加載下面四個位置的application.properties或者application.yml,優先級從上到下依次降低

1)A /config subdirectory of the current directory當前目錄的config子目錄
2)The current directory當前目錄
3)A classpath /config package類路徑的config包
4)The classpath root類根路徑

配置文件中參數的調用:

2.1、@Value註解直接注入

配置文件application.yml:

name: ExternalizedConf

 代碼:

import org.springframework.stereotype.*;
import org.springframework.beans.factory.annotation.*;

@Component
public class MyBean {

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

    // ...

}

測試類:

/**
 * 測試value註解
 */
public class ValueAnnotationTest extends ApplicationTest {

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

    @Test
    public void test(){
        Assert.assertEquals(name, "ExternalizedConf");
    }
}

 

2.2、通過@ConfigurationProperties綁定到結構化對象

配置文件application.yml:

my:
  firstName: yan
  list:
    - name: my name
      description: my description
    - name: another name
      description: another description
  remote-address: 192.168.1.1
  servers:
    - dev.bar.com
    - foo.bar.com
  security:
    username: user1
    password: user1
    roles:
      - USER
      - ADMIN

代碼:

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

import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 類型安全的配置屬性
 * 屬性加入到spring 的Environment中有兩個方法:
 * 1,在本類中加component註解
 * 2,在啓動類上加註解@EnableConfigurationProperties(Config.class)
 * 使用 @ConfigurationProperties,還可以生成meta-data文件,以供IDE使用。(摘取網上內容,需驗證)
 *
 * YAML lists的例子:
 * my:
 *   servers:
 *   - dev.bar.com
 *   - foo.bar.com
 *
 * 嵌套的例子
 *
 *
 * 對屬性字段名字的匹配,如firstName可以匹配如下4種格式的屬性名書寫
 * my.firstName	Standard camel case syntax.
 * my.first-name	Dashed notation, recommended for use in.properties and .yml files.
 * my.first_name	Underscore notation, alternative format for use in .properties and .yml files.
 * MY_FIRST_NAME	Upper case format. Recommended when using a system environment variables.
 *
 *
 * 配置驗證:
 * @Validated
 */
@Component
@ConfigurationProperties(prefix="my")
public class MyConfig {

    private String firstName;

    public String getFirstName() {
        return this.firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    private List<String> servers = new ArrayList<String>();

    public String getServerStr() {
        if(this.servers.size() == 0)
            return "";
        StringBuilder servers = new StringBuilder();
        for(String server : this.servers){
            servers.append(server).append(",");
        }
        servers.setCharAt(servers.length()-1, '\0');
        return servers.toString();
    }

    public void setServers(List<String> servers) {
        this.servers = servers;
    }

    private boolean enabled;

    private InetAddress remoteAddress;


    private final Security security = new Security();

    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    public InetAddress getRemoteAddress() {
        return remoteAddress;
    }

    public void setRemoteAddress(InetAddress remoteAddress) {
        this.remoteAddress = remoteAddress;
    }

    public Security getSecurity() {
        return security;
    }

    class Security {


        private String username;

        private String password;

        private List<String> roles = new ArrayList<>(Collections.singleton("USER"));

        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }

        public List<String> getRoles() {
            return roles;
        }

        public void setRoles(List<String> roles) {
            this.roles = roles;
        }
    }
}

測試類:

import com.example.conf.MyConfig;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

/**
 * 測試ConfigurationProperty
 */
public class ConfigurationPropertyTest extends ApplicationTest {

    private MyConfig myConfig;

    @Autowired
    public void setMyConfig(MyConfig myConfig){
        this.myConfig = myConfig;
    }

    @Test
    public void test(){
        Assert.assertEquals(myConfig.getFirstName(), "yan");
    }
}

2.3、屬性文件中的佔位符

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

2.4、使用PropertySource 註解指定配置文件位置和名稱

可以不使用默認的配置文件名稱和路徑,通過PropertySource 註解在configuration註解的類上指定。

配置文件:在resource目錄下加入文件my.yml

sender_mail: smtp.bitei.cn

代碼:在啓動類中加入PropertySource註解

@SpringBootApplication
@PropertySource("my.yml")
public class Application {

    public static void main( String[] args ) {
        SpringApplication app = new SpringApplication(Application.class);
        app.run();
    }
}

也可以使用ConfigurationProperties註解的location屬性指定自定義配置文件

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章