This rule reports when the Spring @Value annotation injects a simple value that does not contain an expression.
The purpose of the @Value annotation in org.springframework.beans.factory.annotation is to inject a value into a field or
method based on the Spring context after it has been established.
If the annotation does not include an expression (either Spring Expression Language or a property injection), the injected value is a simple constant that does not depend on the Spring context, making the annotation replaceable with a standard field initialization statement.
This not only implies the redundant use of @Value, but could also indicate an error where the expression indicators (#,
$) were omitted by mistake.
This rule does not raise an issue if @Value is applied to a method or method argument, because the annotation has the side effect that
the method is called.
${propertyName} instead of propertyName. #{expression} instead of expression.
@Value("catalog.name") // Noncompliant, this will not inject the property
String catalog;
@Value("${catalog.name}") // Compliant
String catalog;
@Value("book.topics[0]") // Noncompliant, this will not evaluate the expression
Topic topic;
@Value("#{book.topics[0]}") // Compliant
Topic topic;
@Value("Hello, world!") // Noncompliant, this use of @Value is redundant
String greeting;
String greeting = "Hello, world!"; // Compliant