Nullable Value Placeholder Without Default
ID |
java.spring_nullable_value_needs_default |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
best-practice, reliability, spring |
Description
Reports a field or parameter carrying both @Nullable and @Value("${…}") whose placeholder has no : default.
Rationale
@Value("${my.property}") injects a property by name; if the property is undefined when the bean is created, Spring throws rather than injecting null. Marking the same field or parameter @Nullable says the developer already expects the property might be absent — but without a default in the placeholder, that expectation is never reached: the application fails at startup before the nullable field would ever be read.
A #{…} SpEL expression is a different mechanism and is not covered by this rule, and a @Value argument that is not a plain string literal is not resolved.
// Bad - nullable field, but no default if the property is undefined
@Nullable
@Value("${feature.rollout.percentage}")
private Integer rolloutPercentage;
// Bad - the same mistake on a constructor parameter
public RolloutPolicy(@Nullable @Value("${feature.rollout.cohort}") String cohort) {
this.cohort = cohort;
}
Remediation
Add a default after a colon inside the placeholder. Since the field is nullable, #{null} is a reasonable default when there is no sensible fallback value.
// Good - falls back to null when the property is undefined
@Nullable
@Value("${feature.rollout.percentage:#{null}}")
private Integer rolloutPercentage;
public RolloutPolicy(@Nullable @Value("${feature.rollout.cohort:#{null}}") String cohort) {
this.cohort = cohort;
}