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注解激活環境。該注解可以使用邏輯運算符。

6:@ConfigurationProperties和@Value比較

特色 @ConfigurationProperties @Value
寬松綁定 YES NO
元數據支持 YES NO
SpEL表達式 NO YES

7:屬性轉換

可以通過提供ConversionService bean(Bean的名字為conversionService),或者注冊屬性修改器

(通過CustomEditorConfigure bean)或者Converters(帶有標記注解的@ConfigurationPropertiesBinding BeanDefinition)。

時間轉換(Duration),查看java.util.Duration(since jdk1.8)

示例如下:

通過JavaBean形式


/**
* 類描述:
*
* @author liuenyuan
* @date 2019/6/17 17:36
* @describe
* @see java.time.Duration
* @see org.springframework.boot.convert.DurationUnit
* @see ChronoUnit
*/
@ConfigurationProperties(prefix = "app.system")
@Data
public class AppSystemProperties {

   @DurationUnit(ChronoUnit.SECONDS)
   private Duration sessionTimeout = Duration.ofSeconds(30);

   @DurationUnit(ChronoUnit.SECONDS)
   private Duration readTimeout = Duration.ofSeconds(5);
}

通過配置文件形式:application.yml


app:
system:
  session-timeout: 30s
  read-timeout: 5s

其余時間配置形式:

  • ns(納秒)

  • us(微妙)

  • ms(毫秒)

  • s(秒)

  • m(分)

  • h(時)

  • d(天)

Data Sizes轉換(數據大小),查看DataSize(spring5.1支持),@DataSizeUnit

示例如下:

通過JavaBean形式

@ConfigurationProperties(prefix = "app.io")
@Data
public class AppIoProperties {

   @DataSizeUnit(DataUnit.MEGABYTES)
   private DataSize bufferSize = DataSize.ofMegabytes(2);
}

通過配置文件application.properties

app:
io:
bufferSize: 3MB

其余數據大小配置:

  • B(bytes)

  • KB

  • MB

  • GB

  • TB

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM