@ConfigurationProperties

In Spring Boot, the @ConfigurationProperties annotation is used to bind external configuration properties to a JavaBean. This annotation is particularly useful when you want to map properties defined in external configuration files (like application.properties or application.yml) to a Java class. It simplifies the process of reading configuration values and injecting them into your application

Here's a basic example to illustrate how to use @ConfigurationProperties in a Spring Boot application:

Step 1: Create a configuration class

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Getter
@Setter
@ConfigurationProperties(prefix = "example")
public class MyAppProperties {

    private String appName;
    private String version;
    private int maxAllowedUsers;

}

In this example, the @ConfigurationProperties annotation is used with the prefix attribute to specify the common prefix for all properties in the configuration file that will be bound to this class.

Step 2: Configure your application.properties or application.yml file

example.appName=MySpringApp
example.version=1.0
example.maxAllowedUsers=100

Step 3: Use the configuration properties in your application

@SpringBootApplication
public class MySpringBootApplication implements CommandLineRunner {

    @Autowired
    private MyAppProperties myAppProperties;

    public static void main(String[] args) {
        SpringApplication.run(MySpringBootApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        System.out.println("Application Name: " + myAppProperties.getAppName());
        System.out.println("Version: " + myAppProperties.getVersion());
        System.out.println("Max Allowed Users: " + myAppProperties.getMaxAllowedUsers());
    }
}

In this example, the properties defined in application.properties under the example prefix will be automatically mapped to the corresponding fields in the MyAppProperties class.