SoFunction
Updated on 2025-04-13

Interpret the basic usage of @ConfigurationProperties

Basic usage of @ConfigurationProperties

@ConfigurationPropertiesIt is a very useful annotation provided in the Spring Boot framework, which allows developers to automatically bind external configuration properties (such as properties in files) to JavaBean objects. This makes it very simple and intuitive to read properties from configuration files and inject them into components of your application.

In Spring Boot app,@ConfigurationPropertiesUsually with@ComponentOr use it with other Spring-managed component annotations.

When Spring Boot starts, it scans for these with@ConfigurationPropertiesAnnotated classes and automatically bind properties in the configuration file to fields of these classes.

For example:

import ;
import ;

@Component
@ConfigurationProperties(prefix = "app")
public class AppProperties {
private String name;
private int version;
// getters and setters
}

In this example,AppPropertiesThe fields in the class will be automatically bound to the configuration file toappA prefixed property.

For example, ifThe following configurations are found in the file:

properties
=MyApp
=1.0

Then Spring Boot will inject these attribute values ​​intoAppPropertiesin the corresponding field of the class.

Advanced usage of @ConfigurationProperties

In addition to basic attribute binding,@ConfigurationPropertiesIt also supports more complex configurations such as nested properties, lists, and mappings.

Nested properties

You can use nested classes to handle nested properties in configuration files.

@Component
@ConfigurationProperties(prefix = "database")
public class DatabaseProperties {
private String url;
private UserProperties user;

// getters and setters

public static class UserProperties {
private String name;
private String password;

// getters and setters
}
}

In the configuration file, you can configure nested properties like this:

properties

=jdbc:mysql://localhost:3306/mydb 
=root 
=secret

Lists and maps

@ConfigurationPropertiesBind configuration properties to Java's List (List) and Map (Map) types are also supported.

@Component 
@ConfigurationProperties(prefix = "emails") 
public class EmailProperties { 
private List<String> addresses; 
private Map<String, String> aliases; 


// getters and setters 
}

In the configuration file, you can configure it like this:

properties

[0]=user1@ 
[1]=user2@ 
=alice@ 
=bob@

@ConfigurationProperties Verification

You can also use standard Java Bean Validation annotations (e.g.@NotNull@Sizeetc.) Verify configuration properties.

If verification fails, Spring Boot throws an exception at startup.

import ;

import ;



@Component

@ConfigurationProperties(prefix = "app")

@Validated

public class AppProperties {

@NotNull

private String name;



@Size(min = 1, max = 50)

private String description;



// getters and setters

}

Notes:

  • Enable configuration property binding: Make sure your Spring Boot app is enabled@EnableConfigurationPropertiesAnnotation, or will be provided with@ConfigurationPropertiesThe class declaration is@Component, so that Spring Boot can automatically discover and bind configuration properties.
  • Attribute name matching: The attribute name in the configuration file must match the field name of the JavaBean (consider the conversion of camel nomenclature and underscore nomenclature). If they don't match, you need to use@ValueAnnotation to manually bind attributes.
  • Configuration file location@ConfigurationPropertiesDefault fromorRead configuration in the file. You can also define other configuration files and use@PropertySourceAnnotations specify their location.
  • Performance considerations:because@ConfigurationPropertiesAll configuration properties are bound at startup, so if there are many or large configuration properties, it may have an impact on startup time. In this case, consider using@ValueAnnotation to inject the required properties individually.
  • Security: Be careful not to expose sensitive information, such as passwords or keys, in the configuration file. Consider using environment variables or encrypted configuration files to store this information.

In addition to the basic usage and advanced features mentioned above,@ConfigurationPropertiesThere are some other notable points:

Custom prefixes and positions

exist@ConfigurationPropertiesIn the comments, you can passprefixProperties specify the prefix for configuration properties.

This way, Spring Boot will automatically match all properties under the prefix and bind them to the corresponding fields. At the same time, you can also use other methods (e.g.@PropertySource) Specify the location of the configuration file.

Activate a specific configuration file

Spring Boot SupportedProperties to activate specific configuration files. You can create different configuration files for different environments (such as development, testing, production) and choose which configuration file to activate at runtime.

@ConfigurationPropertiesAnnotated classes can also be associated with specific configuration files, thereby achieving different configurations in different environments.

Custom property binding rules

Sometimes, the attribute name in the configuration file may not exactly match the field name of the JavaBean, or you may need to apply some custom transformation logic.

In this case, you can use@ConfigurationPropertiesBindingAnnotated or customizedConverterClass to define its own attribute binding rules.

Listen to configuration changes

Spring Boot also provides@ConfigurationPropertiesAn extended annotation for@NestedConfigurationProperty, which allows you to listen for changes in nested properties and execute specific logic when properties are updated.

This is very useful for scenarios where dynamic responses to configuration changes are required.

Work in concert with other annotations

@ConfigurationPropertiesCan be annotated with other Spring (e.g.@Value@Autowired) Work together to provide more flexible and powerful configuration management capabilities.

You can use multiple annotations in the same class as you want to meet different configuration needs.

Best Practices

  1. Clearly configure prefixes: Assign an explicit configuration prefix to each configuration class to avoid attribute name conflicts.
  2. Verify configuration properties: Use Java Bean Validation to verify configuration properties to ensure the correctness of the configuration.
  3. Documented configuration: Provide clear documentation for configuration properties, including the functions of properties, value ranges, default values, etc., so that other developers can understand and use them.
  4. Avoid hard-coded: Try not to hardcode the value of the configuration property in the code, but use@ConfigurationPropertiesor@ValueAnnotations are read from the configuration file.
  5. Test configuration: Write unit tests to verify that the binding and verification logic of configuration properties is correct.

Summarize

@ConfigurationPropertiesIt is a powerful annotation in Spring Boot, which simplifies the property binding process from configuration files to JavaBeans and improves application flexibility and maintainability.

By using this annotation reasonably, you can manage configuration properties more efficiently and enable more robust and configurable Spring Boot applications. At the same time, some best practices and precautions in use should be paid attention to to ensure the correctness of the configuration and the stability of the application.

The above is personal experience. I hope you can give you a reference and I hope you can support me more.