@ConfigurationProperties versus @Value

In our code, we have used both strongly-type @ConfigurationProperties based classes as well as @Value labeled attributes. It's important to understand the differences before using them in your application.

@Value is old, preceding Spring Boot by years. It is a powerful annotation, able to inject values as well as accept default values. However, it misses several features many of us have come to rely upon when writing Boot apps, as shown in the following table:

Feature

@ConfigurationProperties

@Value

Relaxed binding

Yes

No

Meta-data support

Yes

No

SpEL evaluation

No

Yes

 

This matrix documents three critical features:

  • Relaxed binding: The ability to match server.port, SERVER_PORT, and sErVeR.pOrT to the same attribute is quite valuable.
  • Meta-data support: The ability to include code completion for property settings is also of incredible value, along with hover-over tips. Anything that speeds up developer effort cannot be understated in value.
  • SpEL evaluation: The ability to write SpEL expressions to populate properties.

There is a strong suggestion to start with @ConfigurationProperties. When you bundle together a set of properties inside a POJO, it really is a shortcut for a fist full of @Value attributes. And the property binding is supercharged.

However, when you need SpEL expression support, as we do to get a hold of the application's URI (${vcap.application.uris[0]}), then it's okay to break from @ConfigurationProperties and switch to @Value.

However, if you'll notice, we continue to leverage it inside @ConfigurationProperties. The real hint of doing it wrong is if we try to construct a collection of properties using @Value. Configuration properties is a nice way to build a hierarchy of properties with little effort.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.107.25