Why You Should Stop Using @Value Annotations In Spring (And Use This Instead)

Mikael Svens
4 min readMar 19, 2024

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.

Photo by Tianyi Ma on Unsplash

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.

  1. No separation of configuration and service implementation. We want…

--

--

Mikael Svens

Freelance software engineer. Writing mostly about Java, React, TypeScript and AI. Follower of Jesus. Happily married. Father of 3 lovely boys. Drummer.