How to Put Code inside the @Value Spring Annotation
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…