1. 程式人生 > >Spring Boot配置篇(基於Spring Boot 2.0系列)

Spring Boot配置篇(基於Spring Boot 2.0系列)

1:概述

SpringBoot支援外部化配置,配置檔案格式如下所示:

  • properties files

  • yaml files

  • environment variables

  • command-line arguments

使用外部化配置方式:

  • @Value註解

  • Environment抽象(Spring環境介面抽象)

  • @ConfigurationProperties

  • PropertySource(檔案屬性抽象)

2:自定義屬性

POM內容如下

    <dependencies>
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter</artifactId>
       </dependency>

       <!--生成spring-configuration-metadata.json檔案,提示屬性-->
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-configuration-processor</artifactId>
           <scope>provided</scope>
       </dependency>

       <dependency>
           <groupId>org.projectlombok</groupId>
           <artifactId>lombok</artifactId>
       </dependency>
   </dependencies>

 

當使用Spring Boot開發專案時,Spring Boot會預設讀取classpath下application.properties

application.yml檔案,詳情請檢視原始碼ConfigFileApplicationListener。這種自定義少量

屬性常常通過@Value註解進行載入,但是@Value所在類必須在Spring IOC容器中。

application.yml自定義屬性


hello:
user:
  name: "劉恩源"

讀取該屬性常常通過@Value註解進行讀取。


@Component
@Data
public class HelloUser {
//hello.user.name:default==>>表示當時該屬性在
   //spring Environment沒有找到取預設值default
   @Value("${hello.user.name:default}")
   private String userName;
}


/**
* 類描述: spring boot config
*
* @author liuenyuan
* @date 2019/6/16 11:36
* @describe
* @see org.springframework.beans.factory.annotation.Value
* @see org.springframework.context.annotation.PropertySource
* @see org.springframework.boot.context.properties.ConfigurationProperties
* @see org.springframework.boot.context.properties.EnableConfigurationProperties
* @see org.springframework.core.env.Environment
* @see org.springframework.context.annotation.Profile
* @see org.springframework.context.support.PropertySourcesPlaceholderConfigurer
*/
@SpringBootApplication
public class ConfigApplication {

   public static void main(String[] args) {
       ConfigurableApplicationContext context = SpringApplication.run(ConfigApplication.class, args);
       HelloUser helloUser = context.getBean(HelloUser.class);
       System.out.println(String.format("通過@Value註解讀取自定義的少量屬性: %s", helloUser.getUserName()));
       context.close();
  }
}

@Value註解注入使用情況

轉載自:<https://www.cnblogs.com/wangbin2188/p/9014837.html>

  • 注入普通字串

  • 注入作業系統屬性

  • 注入表示式結果

  • 注入其他Bean屬性

  • 注入檔案資源

  • 注入URL資源

  • 注入${...}來處理placeholder。


   @Value("normal")
   private String normal; // 注入普通字串

   @Value("#{systemProperties['os.name']}")
   private String systemPropertiesName; // 注入作業系統屬性

   @Value("#{ T(java.lang.Math).random() * 100.0 }")
   private double randomNumber; //注入表示式結果

   @Value("#{beanInject.another}")
   private String fromAnotherBean; // 注入其他Bean屬性:注入beanInject物件的屬性another,類具體定義見下面

   @Value("classpath:com/hry/spring/configinject/config.txt")
   private Resource resourceFile; // 注入檔案資源

   @Value("http://www.baidu.com")
   private Resource testUrl; // 注入URL資源

3:將配置檔案屬性賦給實體類

當有許多配置屬性(建議超過5這樣),可以將這些屬性作為欄位來建立一個JavaBean,並將屬性賦給他們。例如

application.yml配置屬性如下:


person:
name: "劉恩源"
age: 21
school: "天津師範大學"

配置屬性類PersonProperties

@ConfigurationProperties註解是將properties配置檔案轉換為bean使用,預設是將application.yml

或者application.properties屬性轉換成bean使用。@PropertySource只支援properties結尾的檔案。

@EnableConfigurationProperties註解的作用是@ConfigurationProperties註解生效,並將屬性

配置類註冊到Spring IOC容器中。 如果需要載入指定配置檔案,可以使用@PropertySource註解。

@ConfigurationProperties(prefix = "person")
@Data
public class PersonProperties {

   private String name;

   private Integer age;

   private String school;
}

@EnableConfigurationProperties({PersonProperties.class})
@Configuration
public class PersonConfiguration {

   private final PersonProperties personProperties;


   public PersonConfiguration(PersonProperties personProperties) {
       this.personProperties = personProperties;
       System.out.println(String.format("PersonProperties: %s", this.personProperties));
  }

   public PersonProperties getPersonProperties() {
       return personProperties;
  }
}

4:自定義配置檔案

上面介紹了讀取預設配置檔案application.yml|application.properties中的配置屬性。當然,我們也可以讀取

自定義的配置檔案中屬性。目前官方使用@PropertySource註解匯入自定義的配置檔案屬性。

建立hello.properties

#load config properties
person.name=劉恩源
person.age=20
person.school=天津師範大學

建立PersonProperties.java

//建立宣告載入properties配置檔案的encoding和name
@ConfigurationProperties(prefix = "person")
@Data
@PropertySource(value = {"classpath:/hello.properties"}, encoding = "UTF-8", name = "hello")
public class PersonProperties {

   private String name;

   private Integer age;

   private String school;
}

建立PersonConfiguration,使用@EnableConfigurationProperties啟用@ConfigurationProperties

註解,將其標註的JavaBean注入到Spring IOC容器中。

@EnableConfigurationProperties({PersonProperties.class})
@Configuration
public class PersonConfiguration {

   private final PersonProperties personProperties;


   public PersonConfiguration(PersonProperties personProperties) {
       this.personProperties = personProperties;
       System.out.println(String.format("PersonProperties: %s", this.personProperties));
  }

   public PersonProperties getPersonProperties() {
       return personProperties;
  }
}

載入指定yml|yaml檔案

配置如下:


public class YamlPropertiesConfiguration {
   
   @Bean
   public static PropertySourcesPlaceholderConfigurer properties() {
       PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
       YamlPropertiesFactoryBean yml = new YamlPropertiesFactoryBean();
       yml.setResources(new ClassPathResource("/hello.yml"));
       configurer.setProperties(yml.getObject());
       return configurer;
  }
}

可以參照我實現的自定義註解@YmlPropertySource,載入yml|yaml檔案,可以大致實現和@PropertySource

註解同樣的功能。

@YmlPropertySource實現載入yml|yaml檔案

5:多環境配置

在企業開發環境中,需要不同的配置環境.SpringBoot使用spring.profiles.active屬性載入不同環境的配置檔案,配置檔案格式為application-{profile}.properties|yml|yaml。{profile}對應環境標識。

  • application-test.yml:測試環境

  • application-dev.yml:開發環境

  • application.prod:生產環境

可以在springboot預設配置檔案application.yml通過配置spring.profiles.active啟用環境。也可以在

特定的類使用@Profile註解啟用環境。該註解可以使用邏輯運算