Contents

Spring Boot中@configurationProperties 简介

1. 简介

Spring Boot 具有许多有用的特性,包括外部化配置和对属性文件中定义的属性的轻松访问。较早的教程 描述了可以完成此操作的各种方法。

我们现在将更详细地探索*@ConfigurationProperties*注解。

2. 设置

本教程使用相当标准的设置。我们首先在pom.xml中添加spring-boot-starter-parent 作为父级:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.6.4</version>
    <relativePath/>
</parent>

为了能够验证文件中定义的属性,我们还需要一个 JSR-303 的实现,hibernate-validator 就是其中之一。

让我们也将它添加到我们的pom.xml中:

<dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-validator</artifactId>
   <version>6.0.16.Final</version>
</dependency>

3. 简单属性

官方文档建议我们将配置属性隔离到单独的 POJO中。

所以让我们从这样做开始:

@Configuration
@ConfigurationProperties(prefix = "mail")
public class ConfigProperties {

    private String hostName;
    private int port;
    private String from;
    // standard getters and setters
}

我们使用*@Configuration*以便 Spring 在应用程序上下文中创建一个 Spring bean。

@ConfigurationProperties最适用于具有相同前缀的分层属性;**因此,我们添加了mail的前缀。

Spring 框架使用标准的 Java bean 设置器,因此我们必须为每个属性声明设置器。

注意:如果我们不在 POJO 中使用*@Configuration*,那么我们需要在主 Spring 应用程序类中添加*@EnableConfigurationProperties(ConfigProperties.class)*来将属性绑定到 POJO 中:

@SpringBootApplication
@EnableConfigurationProperties(ConfigProperties.class)
public class EnableConfigurationDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(EnableConfigurationDemoApplication.class, args);
    }
}

而已!Spring 将自动绑定在我们的属性文件中定义的任何属性,这些属性具有前缀mail并且与ConfigProperties类中的字段之一同名。

Spring 使用一些宽松的规则来绑定属性。因此,以下变体都绑定到属性hostName

mail.hostName
mail.hostname
mail.host_name
mail.host-name
mail.HOST_NAME

因此,我们可以使用以下属性文件来设置所有字段:

#Simple properties
mail.hostname=host@mail.com
mail.port=9000
mail.from=mailer@mail.com

3.1. Spring Boot 2.2

Spring Boot 2.2 开始,Spring通过类路径扫描查找并注册@ConfigurationProperties*类*。@ConfigurationProperties的扫描需要通过添加***@ConfigurationPropertiesScan*注释来明确选择。因此,我们不必使用@Component(以及其他元注释,如@Configuration)来注释这些类, 甚至不必使用@EnableConfigurationProperties

@ConfigurationProperties(prefix = "mail") 
@ConfigurationPropertiesScan 
public class ConfigProperties { 
    private String hostName; 
    private int port; 
    private String from; 
    // standard getters and setters 
}

@SpringBootApplication启用的类路径扫描器会找到ConfigProperties类,即使我们没有用*@Component* 注释这个类。

此外,我们可以使用***@ConfigurationPropertiesScan 注解来扫描配置属性类的自定义位置:*

@SpringBootApplication
@ConfigurationPropertiesScan("com.blogdemo.configurationproperties")
public class EnableConfigurationDemoApplication { 
    public static void main(String[] args) {   
        SpringApplication.run(EnableConfigurationDemoApplication.class, args); 
    } 
}

这样,Spring 将仅在com.blogdemo.properties包中查找配置属性类。

4. 嵌套属性

我们可以在ListsMapsClasses 中拥有嵌套属性。

让我们创建一个新的Credentials类以用于一些嵌套属性:

public class Credentials {
    private String authMethod;
    private String username;
    private String password;
    // standard getters and setters
}

我们还需要更新ConfigProperties类以使用ListMapCredentials类:

public class ConfigProperties {
    private String host;
    private int port;
    private String from;
    private List<String> defaultRecipients;
    private Map<String, String> additionalHeaders;
    private Credentials credentials;
 
    // standard getters and setters
}

以下属性文件将设置所有字段:

#Simple properties
mail.hostname=mailer@mail.com
mail.port=9000
mail.from=mailer@mail.com

#List properties
mail.defaultRecipients[0]=admin@mail.com
mail.defaultRecipients[1]=owner@mail.com

#Map Properties
mail.additionalHeaders.redelivery=true
mail.additionalHeaders.secure=true

#Object properties
mail.credentials.username=john
mail.credentials.password=password
mail.credentials.authMethod=SHA1

5. 在*@Bean方法上使用@ConfigurationProperties*

我们还可以在@Bean注解的方法上使用@ConfigurationProperties*注解。*

当我们想要将属性绑定到我们无法控制的第三方组件时,这种方法可能特别有用。

让我们创建一个简单的Item类,我们将在下一个示例中使用它:

public class Item {
    private String name;
    private int size;
    // standard getters and setters
}

现在让我们看看如何在*@Bean方法上使用@ConfigurationProperties将外部化属性绑定到Item*实例:

@Configuration
public class ConfigProperties {
    @Bean
    @ConfigurationProperties(prefix = "item")
    public Item item() {
        return new Item();
    }
}

因此,任何以项目为前缀的属性都将映射到由 Spring 上下文管理的Item实例。

6. 属性验证

**@ConfigurationProperties使用 JSR-303 格式提供属性验证。**这允许各种整洁的东西。

例如,让我们强制hostName属性:

@NotBlank
private String hostName;

接下来,让我们将authMethod属性的长度设置为 1 到 4 个字符:

@Length(max = 4, min = 1)
private String authMethod;

然后port属性从 1025 到 65536:

@Min(1025)
@Max(65536)
private int port;

最后,from属性必须匹配电子邮件地址格式:

@Pattern(regexp = "^[a-z0-9._%+-][[email protected]](/cdn_cgi/l/email_protection)[a-z0-9.-]+\\.[a-z]{2,6}$")
private String from;

这有助于我们减少代码中的大量if – else条件,并使其看起来更加简洁明了。

如果这些验证中的任何一个失败,则主应用程序将无法以IllegalStateException启动。

Hibernate Validation 框架使用标准的 Java bean getter 和 setter,因此为每个属性声明 getter 和 setter 很重要。

七、属性转换

@ConfigurationProperties支持将多种类型的属性绑定到其对应的 bean 的转换。

7.1. Duration

我们将从将属性转换为Duration对象开始。

这里我们有两个Duration类型的字段:

@ConfigurationProperties(prefix = "conversion")
public class PropertyConversion {
    private Duration timeInDefaultUnit;
    private Duration timeInNano;
    ...
}

这是我们的属性文件:

conversion.timeInDefaultUnit=10
conversion.timeInNano=9ns

结果,字段timeInDefaultUnit的值为 10 毫秒,timeInNano的值为 9 纳秒。

支持的单位是ns、us、ms、s、m、hd,分别表示纳秒、微秒、毫秒、秒、分钟、小时和天。

默认单位是毫秒,这意味着如果我们不指定数值旁边的单位,Spring 会将值转换为毫秒。

我们还可以使用*@DurationUnit*覆盖默认单位:

@DurationUnit(ChronoUnit.DAYS)
private Duration timeInDays;

这是相应的属性:

conversion.timeInDays=2

7.2. DataSize

同样,Spring Boot @ConfigurationProperties支持DataSize类型转换。

让我们添加三个DataSize类型的字段:

private DataSize sizeInDefaultUnit;
private DataSize sizeInGB;
@DataSizeUnit(DataUnit.TERABYTES)
private DataSize sizeInTB;

这些是相应的属性:

conversion.sizeInDefaultUnit=300
conversion.sizeInGB=2GB
conversion.sizeInTB=4

在这种情况下,sizeInDefaultUnit值将是 300 字节,因为默认单位是字节。

支持的单位是B、KB、MB、GBTB。我们还可以使用*@DataSizeUnit* 覆盖默认单位。

7.3. 自定义Converter

我们还可以添加我们自己的自定义Converter来支持将属性转换为特定的类类型。

让我们添加一个简单的类Employee

public class Employee {
    private String name;
    private double salary;
}

然后我们将创建一个自定义转换器来转换此属性:

conversion.employee=john,2000

我们将其转换为Employee类型的文件:

private Employee employee;

我们需要实现Converter接口,然后使用*@ConfigurationPropertiesBinding注解注册我们的自定义Converter*:

@Component
@ConfigurationPropertiesBinding
public class EmployeeConverter implements Converter<String, Employee> {
    @Override
    public Employee convert(String from) {
        String[] data = from.split(",");
        return new Employee(data[0], Double.parseDouble(data[1]));
    }
}

8. 不可变的*@ConfigurationProperties*绑定

从 Spring Boot 2.2 开始,我们可以使用@ConstructorBinding*注解来绑定我们的配置属性*。

这实质上意味着*@ConfigurationProperties* - 注解的类现在可能是不可变 的。

@ConfigurationProperties(prefix = "mail.credentials")
@ConstructorBinding
public class ImmutableCredentials {
    private final String authMethod;
    private final String username;
    private final String password;
    public ImmutableCredentials(String authMethod, String username, String password) {
        this.authMethod = authMethod;
        this.username = username;
        this.password = password;
    }
    public String getAuthMethod() {
        return authMethod;
    }
    public String getUsername() {
        return username;
    }
    public String getPassword() {
        return password;
    }
}

正如我们所见,当使用 @ConstructorBinding 时,我们需要为构造函数提供我们想要绑定的所有参数。

请注意,ImmutableCredentials的所有字段都是最终的。此外,没有设置方法。

此外,需要强调的是,**要使用构造函数绑定,我们需要使用 @EnableConfigurationProperties 或 @ConfigurationPropertiesScan显式启用我们的配置类。

9. Java 16 records

Java 16 引入了 records类型作为JEP 395 的一部分。记录是充当不可变数据的透明载体的类。这使它们成为配置持有者和 DTO 的完美候选者。事实上,我们可以在 Spring Boot 中将 Java 记录定义为配置属性。例如,前面的例子可以重写为:

@ConstructorBinding
@ConfigurationProperties(prefix = "mail.credentials")
public record ImmutableCredentials(String authMethod, String username, String password) {
}

显然,与所有那些嘈杂的 getter 和 setter 相比,它更简洁。

此外,从Spring Boot 2.6 开始,对于单构造函数记录,我们可以删除 @ConstructorBinding注释。但是,如果我们的记录有多个构造函数,则仍应使用*@ConstructorBinding*来标识用于属性绑定的构造函数。