Spring 5 have added support Null-safety of Spring APIs. Now We can also use @Nullable
to indicate optional injection points.
But i am not able to understand use case when we should use @Nullable
dependency ?
spring documentation does not have examples about the @Nullable
dependency
@Component
public class SomeClass {
@Nullable
@Autowired
private MyService service;
public void someMethod()
{
service.someMethod();
}
}
The most know approach to achieve the optional injection is simply to use the @Autowired(required = false) . It will look something like this: @Autowired(required = false) private HelloService helloService; Typically, this works fine and gets us to where we wanted to be.
Annotation Type NullableA common Spring annotation to declare that annotated elements can be null under some circumstance. Leverages JSR-305 meta-annotations to indicate nullability in Java to common tools with JSR-305 support and used by Kotlin to infer nullability of Spring API.
The @Nullable annotation helps you detect: Method calls that can return null. Variables (fields, local variables, and parameters), that can be null.
The @ComponentScan annotation is used to find beans and the corresponding injected with @Autowired annotation. If you followed the Spring Boot typical layout, no need to specify any arguments for @ComponentScan annotation. All component class files are automatically registered with Spring Beans.
Now We can also use @Nullable to indicate optional injection points.
I think that it makes sense if you dependency is not mandatory.
What you could write without @Nullable
:
@Autowired(required = false)
private MyService service;
Now with this code :
@Nullable
@Autowired
private MyService service;
you could use a standard way to convey that the field may be null
.
And according to the javadoc, the standard way allows to take advantage of tools that support this annotation :
Leverages JSR 305 meta-annotations to indicate nullability in Java to common tools with JSR 305 support and used by Kotlin to infer nullability of Spring API.
Note that @Nullable
on a dependency is a case among others.
On the javadoc, you can also read :
A common Spring annotation to declare that annotated elements can be null under some circumstance.
and also :
Should be used at parameter, return value, and field level. Methods override should repeat parent @Nullable annotations unless they behave differently.
So, it makes sense also to decorate method return :
@Nullable
public Foo doThat() {
...
}
or parameters :
public Foo doThat(@Nullable Bar) {
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With