Micronaut - A common mistake with the use of @Value
Micronaut provides io.micronaut.context.annotation.Value
for injecting value from the property source into a variable. Spring framework also provides a similar annotation.
Can you spot the mistake in the below code?
package com.nareshak;
import io.micronaut.context.annotation.Value;
import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.Produces;
@Controller("/hello")
public class HelloController {
@Value("greeting.message")
private String message;
@Get("/")
@Produces(MediaType.TEXT_PLAIN)
public String index() {
return message;
}
}
If you wish to understand the usage of @Value
annotation, read my post on reading from property sources
If you observe, I have passed the string "greeting.message" to @Value
annotation. This code results in the endpoint returning the "greeting.message", while we intended the endpoint to return the value of "greeting.message" from the appropriate property source.
Supplying the key instead of the expression evaluating the key is typical mistake developers end up with accidentally. I have committed this mistake a few times. I have also seen several developers committing the same mistake. Most of the time it is quite easy to escape from your eyes when you are reading the code.
The correct code looks as follows.
@Value("${greeting.message}")
private String message;
Fortunately, Micronaut has a solution for it. The solution is in the form of io.micronaut.context.annotation.Property
annotation. Let's refactor the code to make use of the @Property
annotation.
@Property(name = "greeting.message")
private String message
@Property
annotation takes the property source name as an attribute and injects the value from the property source to the field, message in the above example.
Note that @Value
is still a handy alternative as you could combine the values from multiple keys and perform some customisations such as concatenating multiple values from the property source.