Spring Boot lab (part 6): Handling configuration
What will be done here?
In the third part of this series on Spring Boot, we implemented a service that calls Github’s API to retrieve data on a user’s repositories.
So far we use a hard-coded string for the URL. This might be ok for test or demonstration purposes. In real applications it is better to store the URL (or parts of it) in properties.
Spring provides a couple of ways to read properties and in the following two of them are described.
Using @Configuration
A class that is annotated with @Configuration
will be handled as a bean. Spring loads the properties at application start and stores the values in member variables of the class.
In the context of the sample application we could store parts of the URL:
The member variables are annotated with @Value
followed by a parameter that represents the key in the properties file.
The properties themselves are stored in the file application.properties
that is located in the src/main/resources
folder.
Next, we can use the values in the service class
Using @ConfigurationProperties
Another approach to load such properties is to use @ConfigurationProperties
followed by a parameter called prefix.
Here we do not need to annotate the member variables. However, their names have to match exactly the naming in the properties file.
Classes annotated with @ConfigurationProperties
are no treated as beans. When the application is started, the following error occurs:
To resolve this, the annotation @EnableConfigurationProperties
is required in the main class:
The annotation takes the configuration class as parameter.