Why You Should Stop Using @Value Annotations In Spring (And Use This Instead)
If you have been working with Java and Spring Boot, I’m sure you have come across the @Value
annotation. I’m here to show you an alternative to use instead — which is much better than using the @Value
way of doing it.
Let’s have a look at the classic @Value
annotation in Spring, it may look something like this:
The @Value
annotation can be used for injecting values into Spring managed beans. In this example we have a service that is responsible for managing JSON Web Tokens or JWT:s for short.
Here we try to inject the client secret from the application.properties
file. The secret is a configuration and not something we would want to hardcode.
We’ve also defined a default value from the constant DEFAULT_SECRET
if the property is not found.
So what are the disadvantages of this approach?
Here are the three main disadvantages of using this approach. I will discuss every one in more detail below.
- No separation of configuration and service implementation. We want…