search
HomeJavajavaTutorialHow to use @ConfigurationProperties in SpringBoot

How to use @ConfigurationProperties in SpringBoot

May 19, 2023 am 11:10 AM
springboot@configurationproperties

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:亿速云. If there is any infringement, please contact admin@php.cn delete
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor