This content originally appeared on DEV Community and was authored by Abdulcelil Cercenazi
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 
@Componentannotation is to tell Spring to manage this class as a bean and provide it for injection. - The 
@ConfigurationPropertiesis 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 
@Setteris to enable@ConfigurationPropertiesto populate the values in theDemoTestConfigsclass. 
  
  
  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.
Code On GitHub ?
This content originally appeared on DEV Community and was authored by Abdulcelil Cercenazi
Abdulcelil Cercenazi | Sciencx (2021-09-04T22:57:43+00:00) Read Spring Properties Like a Pro. Retrieved from https://www.scien.cx/2021/09/04/read-spring-properties-like-a-pro/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.