ConfigurationProperties easily manages application configuration information
What is @ConfigurationProperties
@ConfigurationProperties
The purpose of annotation is to inject property values from external configuration files into a Java Bean.
The advantage of this is that it can easily bind the attribute values in the configuration file to Java Bean objects, making the reading and management of configuration attributes more convenient.
pass@ConfigurationProperties annotation
, we can easily map attribute values in configuration files into a POJO (Plain Old Java Object) class in Spring Boot application, thereby achieving type-safe attribute access.
This way, instead of manually writing code to read properties in the configuration file, we can inject property values in the configuration file directly into a predefined Java Bean object and then use these property values directly in the code.
Case implementation
Suppose there is a file that contains the following properties:
=John =30
We can create a UserProperties class and map these property values into the class using the @ConfigurationProperties annotation:
import ; import ; @Data @Component @ConfigurationProperties(prefix = "") public class UserProperties { private String name; private int age; }
Then, we can inject the UserProperties object directly into the code and access the property values in it:
@Service public class UserService { private final UserProperties userProperties; public UserService(UserProperties userProperties) { = userProperties; } public void displayUserInfo() { ("User Name: " + ()); ("User Age: " + ()); } }
By using the @ConfigurationProperties annotation, we can easily inject property values from external configuration files into UserProperties objects without hard-coded these property values in the code, which can improve the maintainability and flexibility of the code.
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.