The @ConfigurationProperties annotation in Spring Boot is used to bind external configuration properties to a Java class. This allows for a centralized configuration management approach where configuration properties can be easily managed and modified outside of the code.
Here’s an example of how to use @ConfigurationProperties in a Spring Boot application:
First, create a Java class that represents the configuration properties you want to bind. The class should have fields that match the property names and types:
@ConfigurationProperties(prefix = "myapp")
public class MyAppProperties {
private String name;
private int port;
private boolean enabled;
// getters and setters
}
In this example, the class represents properties with the prefix "myapp". The prefix attribute is used to specify the prefix for the configuration properties that will be bound to this class.
Next, enable configuration properties scanning in your Spring Boot application by adding the @EnableConfigurationProperties annotation to one of your configuration classes:
@SpringBootApplication
@EnableConfigurationProperties(MyAppProperties.class)
public class MyApp {
// ...
}
This enables scanning for @ConfigurationProperties-annotated classes, and the MyAppProperties class will be available for binding.
Finally, you can use the @Autowired annotation to inject the MyAppProperties class into other classes in your application:
@Service
public class MyService {
private final MyAppProperties properties;
@Autowired
public MyService(MyAppProperties properties) {
this.properties = properties;
}
public void doSomething() {
// access the properties
String name = properties.getName();
int port = properties.getPort();
boolean enabled = properties.isEnabled();
// ...
}
}
In this example, the MyService class has an instance of MyAppProperties injected via the constructor. The properties can then be accessed using the getter methods.
Overall, using @ConfigurationProperties in Spring Boot allows for easy management of configuration properties outside of the code, and centralizes the configuration in a single location.