@ConfigurationProperties

@ConfigurationProperties can be used to map configuration values onto a strongly typed configuration class. To demonstrate this we will modify the example from above to use @ConfigurationProperties instead.

Create a configuration class ApplicationProperties.

A configuration class with one configuration value.
@ConfigurationProperties (1)
@Component
@Data (2)
public class ApplicationProperties {
    private String applicationKey;  (3)
}
1 The @ConfigurationProperties annotation specifies that this is a configuration class.
2 We use this Lombok annotation to generate getters and setters which Spring Boot require for setting the field appropriately.
3 This field will map to the entry from the YAML file. The field name and the YAML key must match.

Modify your StartupLogger class to the one below.

A component which displays a configuration value from a configuration class.
@Component
@Slf4j
@RequiredArgsConstructor
public class StartupLogger {

    private final ApplicationProperties applicationProperties; (1)

    @Bean
    public Void dummyBean() {
        LOG.info( "Your application key is: {}", applicationProperties.getApplicationKey());  (2)
        return null;
    }
}
1 The configuration class is wired.
2 The applicationKey YAML entry is now automatically mapped onto the configuration class by Spring and can be retrieved through the getter.

The advantages of doing this are:

  • Configuration values belonging to the same 'object' can be bundled. For example, you can bundle FTP properties like hostname, username and password into an FtpProperties configuration class.

  • Instead of having multiple @Value annotations, a single configuration class has to be mapped, making your code less verbose.

  • You can take advantage of Spring validation, to validate configuration values at application startup.

Have a look at Spring Boot Externalized Configuration for more information.

In the next section we will learn how to specify different values per configuration item, for example to differentiate between development and production environments.