Using similar approach to the one from https://stackoverflow.com/a/60442151/11770752
But instead of AllArgsConstructor
you can use the RequiredArgsConstructor
.
Consider following applications.properties
myprops.example.firstName=Peter
myprops.example.last-name=Pan
myprops.example.age=28
Note: Use consistency with your properties, i just wanted to show-case that both were correct (fistName
and last-name
).
Java Class pickping up the properties
@Getter
@ConstructorBinding
@RequiredArgsConstructor
@ConfigurationProperties(prefix = "myprops.example")
public class StageConfig
{
private final String firstName;
private final Integer lastName;
private final Integer age;
// ...
}
Additionally you have to add to your build-tool a dependency.
build.gradle
annotationProcessor('org.springframework.boot:spring-boot-configuration-processor')
or
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>${spring.boot.version}</version>
</dependency>
If you take it one step further to provide nice and precise descriptions for you configurations, consider creating a file additional-spring-configuration-metadata.json
in directory src/main/resources/META-INF
.
{
"properties": [
{
"name": "myprops.example.firstName",
"type": "java.lang.String",
"description": "First name of the product owner from this web-service."
},
{
"name": "myprops.example.lastName",
"type": "java.lang.String",
"description": "Last name of the product owner from this web-service."
},
{
"name": "myprops.example.age",
"type": "java.lang.Integer",
"description": "Current age of this web-service, since development started."
}
}
(clean & compile to take effect)
At least in IntelliJ, when you hover over the properties inside application.propoerties
, you get a clear despriction of your custom properties. Very useful for other developers.
This is giving me a nice and concise structure of my properties, which i am using in my service with spring.