rspec/rules/S6804/java/rule.adoc
2023-10-19 11:40:26 +02:00

80 lines
2.6 KiB
Plaintext

This rule reports when the Spring `@Value` annotation injects a simple value that does not contain an expression.
== Why is this an issue?
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.
=== Exceptions
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.
== How to fix it
- If a property is to be injected, use `${propertyName}` instead of `propertyName`.
- If a SpEL expression is to be evaluated, use `#{expression}` instead of `expression`.
- If you intend to initialize a field with a simple value or with an expression that does not depend on the Spring context, use a standard field initialization statement.
=== Code examples
==== Noncompliant code example
[source,java,diff-id=1,diff-type=noncompliant]
----
@Value("catalog.name") // Noncompliant, this will not inject the property
String catalog;
----
==== Compliant solution
[source,java,diff-id=1,diff-type=compliant]
----
@Value("${catalog.name}") // Compliant
String catalog;
----
==== Noncompliant code example
[source,java,diff-id=2,diff-type=noncompliant]
----
@Value("book.topics[0]") // Noncompliant, this will not evaluate the expression
Topic topic;
----
==== Compliant solution
[source,java,diff-id=2,diff-type=compliant]
----
@Value("#{book.topics[0]}") // Compliant
Topic topic;
----
==== Noncompliant code example
[source,java,diff-id=3,diff-type=noncompliant]
----
@Value("Hello, world!") // Noncompliant, this use of @Value is redundant
String greeting;
----
==== Compliant solution
[source,java,diff-id=3,diff-type=compliant]
----
String greeting = "Hello, world!"; // Compliant
----
== Resources
=== Documentation
- https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/annotation/Value.html[Spring Framework API - Annotation Interface Value]
=== Articles & blog posts
- https://www.baeldung.com/spring-value-annotation[Baeldung - A Quick Guide to Spring @Value]
- https://www.digitalocean.com/community/tutorials/spring-value-annotation[DigitalOcean - Spring @Value Annotation]