Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use @ ConfigurationProperties in SpringBoot

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "how to use @ ConfigurationProperties in SpringBoot". The content in the article is simple and clear, easy to learn and understand. Please follow the editor's train of thought to study and learn "how to use @ ConfigurationProperties in SpringBoot".

Add dependencies

First we need to add Spring Boot dependencies:

Org.springframework.boot 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 reads all attributes that start with mail in the properties file and matches the fields in bean:

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

Spring's attribute name matching supports many formats, all of which can be matched with hostName as shown below:

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 to 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 look for the config file in the com.flydean.config package.

Property nesting

We can nest class,list,map. Let's take an example to create a normal POJO:

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

Then create a nested profile:

@ 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 properties file is 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=truenestmail.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;}

Take a look at how to use:

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

Attribute verification

@ ConfigurationProperties can use the standard JSR-303 format for attribute validation. Let's give 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.9% Pattern -] + @ [a-z0-9.9 -] +\. [Amurz] {2jue 6} $") private String from;}

If our attribute does not meet the appeal criteria, 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: minimum 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 transformations. Let's take Duration and DataSize as examples:

We define two fields for Duration:

@ 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 properties can take units. The optional units are: ns, us, ms, s, m, h and d, corresponding to nanoseconds, subtleties, milliseconds, seconds, minutes, hours, and days, respectively. The default unit is milliseconds. We can also specify units in the comments:

@ DurationUnit (ChronoUnit.DAYS) private Duration timeInDays

The corresponding configuration files are as follows:

Conversion.timeInDays=2

Let's take a look at how DataSize works:

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

Corresponding property 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;}

Corresponding property file:

Conversion.employee=john,2000

We need to implement a transformation 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]));}}

Thank you for reading, the above is the content of "how to use @ ConfigurationProperties in SpringBoot". After the study of this article, I believe you have a deeper understanding of how to use @ ConfigurationProperties in SpringBoot, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report