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

1:概述

SpringBoot支持外部化配置,配置文件格式以下所示:html

  • properties filesjava

  • yaml filesspring

  • environment variablesjson

  • command-line argumentsspringboot

使用外部化配置方式:session

  • @Value注解app

  • Environment抽象(Spring环境接口抽象)dom

  • @ConfigurationPropertieside

  • PropertySource(文件属性抽象)spring-boot

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

相关文章
相关标签/搜索