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

it2022-05-05  83

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@Datapublic 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 */@SpringBootApplicationpublic 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")@Datapublic class PersonProperties {​    private String name;​    private Integer age;​    private String school;}​@EnableConfigurationProperties({PersonProperties.class})@Configurationpublic 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 propertiesperson.name=刘恩源person.age=20person.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})@Configurationpublic 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宽松绑定YESNO元数据支持YESNOSpEL表达式NOYES

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")@Datapublic 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")@Datapublic class AppIoProperties {​    @DataSizeUnit(DataUnit.MEGABYTES)    private DataSize bufferSize = DataSize.ofMegabytes(2);}

通过配置文件application.properties

app: io: bufferSize: 3MB

其余数据大小配置:

B(bytes)

KB

MB

GB

TB

 

转载于:https://www.cnblogs.com/liuenyuan1996/p/11039962.html


最新回复(0)