Home  >  Article  >  Java  >  How to use @ConfigurationProperties in SpringBoot

How to use @ConfigurationProperties in SpringBoot

王林
王林forward
2023-05-19 11:10:061423browse

Add dependencies

First we need to add Spring Boot dependencies:

org.springframework.boot < ;artifactId>spring-boot-starter-parent

A simple Example

@ConfigurationProperties needs to be used in conjunction with @Configuration. We usually configure it in a POJO:

@Data@Configuration@ConfigurationProperties(prefix = "mail")public class ConfigProperties { private String hostName; private int port; private String from;}

The above example will read all the properties starting with mail in the properties file and match them with the fields in the bean:

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

Spring’s property name matching supports many formats. As shown below, all formats can be matched with hostName. Match:

mail.hostNamemail.hostnamemail.host_namemail.host-namemail.HOST_NAME

If you don’t want to use @Configuration, you need to manually import the configuration file in the @EnableConfigurationProperties annotation as follows:

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

We can also Specify the path of the Config file in @ConfigurationPropertiesScan:

@SpringBootApplication@ConfigurationPropertiesScan("com.flydean.config") public class ConfigPropApp { public static void main(String[] args) { SpringApplication.run(ConfigPropApp. class,args); }}

In this case, the program will only search for the config file in the com.flydean.config package.

Attribute nesting

We can nest class, list, and map. Let’s take an example and create an ordinary POJO first:

@Datapublic class Credentials { private String authMethod; private String username; private String password;}

Then create a nested configuration file:

@Data@Configuration@ConfigurationProperties(prefix = "nestmail ") public class NestConfigProperties { private String host; private int port; private String from; private List defaultRecipients; private Map additionalHeaders; private Credentials credentials;}

The corresponding property files are as follows :

# nest Simple propertiesnestmail.hostname=mailer@mail.comnestmail.port=9000nestmail.from=mailer@mail.com#List propertiesnestmail.defaultRecipients[0]=admin@mail.comnestmail.defaultRecipients[1] =owner@mail.com#Map Propertiesnestmail.additionalHeaders.redelivery=trueenestmail.additionalHeaders.secure=true#Object propertiesnestmail.credentials.username=johnnestmail.credentials.password=passwordnestmail.credentials.authMethod=SHA1

@ConfigurationProperties and @Bean

@ConfigurationProperties can also be used with @Bean as follows:

@Datapublic class Item { private String name; private int size;}

See how to use:

@Data@Configurationpublic class BeanConfigProperties { @Bean @ConfigurationProperties(prefix = "item") public Item item() { return new Item(); }}

Property Validation

@ConfigurationProperties can use the standard JSR-303 format for property validation. Let's take an example:

@Data@Validated@Configuration@ConfigurationProperties(prefix = "mail")public class ConfigProperties { @NotEmpty private String hostName; @Min(1025) @Max(65536) private int port; @Pattern(regexp = "^[a-z0-9._% -] @[a-z0-9.-] \\.[a-z]{2,6}$") private String from;}

If our properties do not meet the appeal conditions, the following exception may occur:

Binding to target org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'mail' to com .flydean.config.ConfigProperties$$EnhancerBySpringCGLIB$$f0f87cb9 failed: Property: mail.port Value: 0 Reason: The minimum value cannot be less than 1025 Property: mail.hostName Value: null Reason: Cannot be empty Action: Update your application's configurationProcess finished with exit code 1

Attribute conversion

@ConfigurationProperties also supports multiple attribute conversions. Below we take Duration and DataSize as examples:

We define two Duration fields:

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

Define these two fields in the properties file :

conversion.timeInDefaultUnit=10conversion.timeInNano=9ns

We see that the above attributes can have units. Optional units are: ns, us, ms, s, m, h and d, corresponding to nanoseconds, microseconds, milliseconds, seconds, minutes, hours and days respectively. The default unit is milliseconds. We can also specify the unit in the annotation:

@DurationUnit(ChronoUnit.DAYS)private Duration timeInDays;

The corresponding configuration file is as follows:

conversion.timeInDays=2

Let’s take a look at how to use DataSize:

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

Corresponding properties file:

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

Datasize supports B, KB, MB, GB and TB.

Custom Converter

The same Spring Boot also supports custom attribute converters. Let’s first define a POJO class:

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

The corresponding properties file:

conversion.employee=john,2000

We need to implement a conversion class of the Converter interface ourselves:

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

The above is the detailed content of How to use @ConfigurationProperties in SpringBoot. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete