Spring 5 :使用@Nullable 的可选注入点
Spring 5 :optional injection points using @Nullable
Spring 5 添加了 Spring API 的空安全支持。现在我们还可以使用 @Nullable
来表示可选的注入点。
但是我无法理解我们应该使用 @Nullable
依赖项的用例?
spring 文档没有关于 @Nullable
依赖性
的示例
@Component
public class SomeClass {
@Nullable
@Autowired
private MyService service;
public void someMethod()
{
service.someMethod();
}
}
Now We can also use @Nullable to indicate optional injection points.
我认为如果你的依赖不是强制性的,那是有道理的。
没有 @Nullable
你可以写什么:
@Autowired(required = false)
private MyService service;
现在使用此代码:
@Nullable
@Autowired
private MyService service;
您可以使用标准方式来传达该字段可能是 null
。
根据 javadoc,标准方式允许利用支持此注释的工具:
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.
请注意 @Nullable
依赖项是其中的一个例子。
在javadoc上,您还可以阅读:
A common Spring annotation to declare that annotated elements can be
null under some circumstance.
还有:
Should be used at parameter, return value, and field level. Methods
override should repeat parent @Nullable annotations unless they behave
differently.
所以,装饰方法也很有意义 return :
@Nullable
public Foo doThat() {
...
}
或参数:
public Foo doThat(@Nullable Bar) {
...
}
Spring 5 添加了 Spring API 的空安全支持。现在我们还可以使用 @Nullable
来表示可选的注入点。
但是我无法理解我们应该使用 @Nullable
依赖项的用例?
spring 文档没有关于 @Nullable
依赖性
@Component
public class SomeClass {
@Nullable
@Autowired
private MyService service;
public void someMethod()
{
service.someMethod();
}
}
Now We can also use @Nullable to indicate optional injection points.
我认为如果你的依赖不是强制性的,那是有道理的。
没有 @Nullable
你可以写什么:
@Autowired(required = false)
private MyService service;
现在使用此代码:
@Nullable
@Autowired
private MyService service;
您可以使用标准方式来传达该字段可能是 null
。
根据 javadoc,标准方式允许利用支持此注释的工具:
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.
请注意 @Nullable
依赖项是其中的一个例子。
在javadoc上,您还可以阅读:
A common Spring annotation to declare that annotated elements can be null under some circumstance.
还有:
Should be used at parameter, return value, and field level. Methods override should repeat parent @Nullable annotations unless they behave differently.
所以,装饰方法也很有意义 return :
@Nullable
public Foo doThat() {
...
}
或参数:
public Foo doThat(@Nullable Bar) {
...
}