Spring 的注释类型需要弃用

Spring's Annotation Type Required deprecation

Spring 的 Annotation Type Required 被标记为已弃用

Deprecated. as of 5.1, in favor of using constructor injection for required settings (or a custom InitializingBean implementation)

相关RequiredAnnotationBeanPostProcessor

相同

不过不知道替换的是什么,看来应该是没有了。

此更改是否会阻止我们将方法标记为必需,除非它是构造函数方法的一部分?防止在 class 创建时出现意外异常?

注解注入bean的三种方式:

字段注入

@Autowired
private FooService fooService;

Setter注入

private FooService fooService;

@Autowired
public void setFooService(FooService fooService) {
    this.fooService = fooService
}

构造函数注入(这是提到的替换)

private final FooService fooService;

@Autowired
public MyComponent(FooService fooService) {
    this.fooService = fooService;
}

如您所见,声明服务 final 的唯一方法是使用构造函数注入,它取代了 @Required 注释,因为它强制 class 的用户用所需的服务实例化它。用户不一定是Spring,也可以是简单的单元测试

您应该对强制依赖项使用构造函数注入,对可选依赖项使用 setter 注入,而不是字段注入。 一些原因:

  • 需要哪些依赖,大家一目了然
  • 它使测试更容易
  • 你可以让你的对象不可变

延伸阅读:

更新:非注释构造函数注入

正如一位评论员想知道 final 字段用 @Autowired 注释而构造函数没有注释:

If a class only declares a single constructor to begin with, it will always be used, even if not annotated.

https://docs.spring.io/spring-framework/docs/5.2.5.RELEASE/javadoc-api/org/springframework/beans/factory/annotation/Autowired.html ("Autowired Constructors")

但即使在这种情况下没有必要注释构造函数,我仍然会这样做:它记录了代码,如果有人添加另一个(未注释的)构造函数,代码仍然有效。

是的,它已被弃用,但您仍然可以通过在 xml 文件中提及来使用它。

<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor" />