41 lines
1.5 KiB
Plaintext
41 lines
1.5 KiB
Plaintext
SpEL, the Spring Expression Languages allows developers fine-grained control over the values injected into fields and parameters.
|
|
Using the `@Value` annotation, it is possible to inject values from sources such as system properties.
|
|
|
|
== Why is this an issue?
|
|
|
|
The `@Value` annotation does not guarantee that the property is defined.
|
|
Particularly if a field or parameter is annotated as nullable, it indicates that the developer assumes that the property may be undefined.
|
|
|
|
An undefined property may lead to runtime exceptions when the Spring framework tries to inject the autowired dependency during bean creation.
|
|
|
|
This rule raises an issue when a nullable field or parameter is annotated with `@Value` and no default value is provided.
|
|
|
|
== How to fix it
|
|
Add a default value to the `@Value` annotation.
|
|
A default value can be supplied by using the colon (`:`) operator.
|
|
As the field is nullable, the default value should most likely be `#{null}`.
|
|
|
|
=== Code examples
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,java,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
@Nullable
|
|
@Value("${my.property}") // Noncompliant, no default value is provided, even though the field is nullable
|
|
private String myProperty;
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,java,diff-id=1,diff-type=compliant]
|
|
----
|
|
@Nullable
|
|
@Value("${my.property:#{null}}") // Compliant, a default value is provided
|
|
private String myProperty;
|
|
----
|
|
|
|
== Resources
|
|
=== Articles & blog posts
|
|
* Baeldung - https://www.baeldung.com/spring-value-defaults[Using Spring @Value With Defaults]
|