How to Put Code inside the @Value Spring Annotation

Daniele Quero, PhD
Geek Culture
Published in
2 min readApr 19, 2022

--

Photo From: https://www.cleanpng.com/png-spring-framework-software-framework-java-applicati-6290527/

The @Value annotation allows injecting values into classes fields (as well as other annotations inject implementations of interfaces, like @Autowired).

For example:

@Value("hello mama")
private String myInjectedString;

Here we inject a string literal value into our field, we could have done it with any other type. Quite useless but helps to understand the annotation usage.

If you are working with a Spring application, chances are you already have a properties file, usually in a YAML format.

In this case, the @Value annotation may tap into the properties file, let’s have this simple example:

Here I put a tree of properties to also show how to access them.

@Value(${parent.child.field1})
private String field1;
@Value(${parent.child.field2})
private String field2;

Using the dot notation, we can browse through the properties down to the one we need. The annotation, then, on top of the java field…

--

--

Daniele Quero, PhD
Geek Culture

A professional developer with passion for game developing and skill-growing. A former Nuclear Physics Researcher who changed his life to pursue his dreams