Configuration Management Is Important ☝️
The necessity of reading configuration in a clean, organized way is growing rapidly especially with the spread of cloud application development and micro-service architecture which requires a lot of integration and connection settings.
What's Wrong With The Typical Way Of Config Reading 🤷
Nothing. However, it can get complicated and messy when we want to inject many of those configs in our code.
Let's look at an example with a single properties file and a test
application.properties ⚙️
demo.test.name=testName
demo.test.age=16
DemoApplicationTests.java
@SpringBootTest
class DemoApplicationTests {
@Value("${demo.test.name}")
private String name;
@Value("${demo.test.age}")
private Integer age;
@Test
void loadProperty() {
assertEquals("testName", name);
assertEquals(16, age);
}
}
Now, imagine we have 5 or 10 of those properties, that would cause our code to be cluttered and hard to follow 🥴
@ConfigurationProperties To The Rescue 🤠
It allows us to inject values from the application.properties
file into a custom class.
@Component
@ConfigurationProperties(prefix = "demo.test")
@Setter
@Getter
public class DemoTestConfigs
{
private String name;
private Integer age;
}
- The
@Component
annotation is to tell Spring to manage this class as a bean and provide it for injection. - The
@ConfigurationProperties
is what does the magic- It looks inside the property files in the class path and loads the properties that start with
demo.test
- It looks inside the property files in the class path and loads the properties that start with
- The Lombok
@Setter
is to enable@ConfigurationProperties
to populate the values in theDemoTestConfigs
class.
We can then simply inject the DemoTestConfigs
bean into our services. 🤝
Let's check it in a test
@SpringBootTest
public class ConfigurationPropertiesTest
{
@Autowired
private DemoTestConfigs demoTestConfigs;
@Test
public void loadPropertiesUsingConfigurationProperties(){
assertEquals("testName", demoTestConfigs.getName());
assertEquals(16, demoTestConfigs.getAge());
}
}
Conclusion 👇
We've seen how @ConfigurationProperties
helps us bundle our similar configurations into a single component class which we can inject and use instead of specifying each and every one of them.
Top comments (2)
We can easily do this using Environment as well
I think we can :D Haven't tried before though. If you have any resources can you share them with us?