DEV Community

Cover image for Read Spring Properties Like a Pro
Abdulcelil Cercenazi
Abdulcelil Cercenazi

Posted on

Read Spring Properties Like a Pro

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
Enter fullscreen mode Exit fullscreen mode

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);  
  }  
}
Enter fullscreen mode Exit fullscreen mode

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;  
}
Enter fullscreen mode Exit fullscreen mode
  • 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
  • The Lombok @Setter is to enable @ConfigurationProperties to populate the values in the DemoTestConfigs 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());  
  }  
}
Enter fullscreen mode Exit fullscreen mode

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 💻

Discussion (2)

Collapse
diasmvds profile image
Darshana Dias

We can easily do this using Environment as well

Collapse
jarjanazy profile image
Abdulcelil Cercenazi Author

I think we can :D Haven't tried before though. If you have any resources can you share them with us?