2

我是弹簧框架的新手。我尝试使用两种注入方法(Setter 和构造函数)注入依赖项。我期待在 setter 注入中定义的输出,因为它被构造函数注入覆盖。但是,我收到了类似的错误消息

Bean创建异常:未找到默认构造函数

如果我们同时应用两种注入方法,它会抛出错误吗?

4

1 回答 1

1

我尝试使用两种注入方法(Setter 和构造函数)注入依赖项。

你应该能够做到这一点。根据 Spring 版本,结果可能会有所不同,但我可以确认它适用于 Spring 5 版本。

你的错误:

Bean 创建异常:未找到默认构造函数。

认为带有参数的构造函数不被 Spring 视为自动装配 bean 的一种方式。
在旧的 Spring 版本(3 和更少,也许我不记得 4)中,您必须@Autowired在构造函数中指定以使 Spring 意识到它。
所以你应该声明:

@Autowired
public void setMyDep(MyDep myDep) {
    this.myDep = myDep;
}

@Autowired
public FooBean(MyOtherDep myOtherDep) {
    this.myOtherDep = myOtherDep;
}

在最近的 Spring 版本中,@Autowired不再需要声明:

@Autowired
public void setMyDep(MyDep myDep) {
    this.myDep = myDep;
}

public FooBean(MyOtherDep myOtherDep) {
    this.myOtherDep = myOtherDep;
}
于 2018-07-11T18:26:21.203 回答