Search code examples
springnullable

Spring 5 :optional injection points using @Nullable


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();       
        } 

    }

Solution

  • 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) {
       ...
    }