java – 当存在多个构造函数时,使用autowire =“constructor”进行依赖注入?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – 当存在多个构造函数时,使用autowire =“constructor”进行依赖注入?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1517字,纯文字阅读大概需要3分钟。
内容图文
![java – 当存在多个构造函数时,使用autowire =“constructor”进行依赖注入?](/upload/InfoBanner/zyjiaocheng/817/b38e04b81e6143cf9cb2297299a0246a.jpg)
我有下面的构造函数的文本编辑器类
public class TextEditor {
private SpellChecker spellChecker;
private SpellChecker1 spellChecker1;
private SpellChecker2 spellChecker2;
public TextEditor(SpellChecker spellChecker) {
this.spellChecker = spellChecker;
}
public TextEditor(SpellChecker2 spellChecker2) {
this.spellChecker2 = spellChecker2;
}
public TextEditor(SpellChecker spellChecker, SpellChecker1 spellChecker1,SpellChecker2 spellChecker2) {
this.spellChecker = spellChecker;
this.spellChecker1 = spellChecker1;
this.spellChecker2 = spellChecker2;
}
public TextEditor(SpellChecker spellChecker, SpellChecker1 spellChecker1) {
this.spellChecker = spellChecker;
this.spellChecker1 = spellChecker1;
}
}
在春天豆我有
<bean id="textEditor" class="com.TextEditor" autowire="constructor">
</bean>
我观察到的是具有两个参数的构造函数被一致地调用.是随机的吗?不应该
spring throw exception becoz它不知道需要调用哪个构造函数?
解决方法:
这是Spring自动构建器的结果.
它做的第一件事就是获取所有bean类的构造函数并对它们进行排序,首先将公共构造函数放入减少的参数数量,然后再将所有非公共构造函数放入参数数量减少的情况.这些是候选构造函数.
然后迭代遍历这些候选者,尝试从BeanFactory生成参数.如果它不能因为bean丢失或出于其他原因,它会跳过候选者.如果它成功找到参数,它会根据许多因素(参数列表长度,参数类型与参数的接近程度等等)为当前候选构造函数提供权重.然后检查前一个候选人的体重,如果一个人比另一个人好,则交换他们.
如果在此过程结束时有候选构造函数,Spring将使用它.
如果你说Spring在你的3 arg构造函数中使用你的2 arg构造函数,那么这意味着你的3 arg构造函数中没有一个类型的bean.
内容总结
以上是互联网集市为您收集整理的java – 当存在多个构造函数时,使用autowire =“constructor”进行依赖注入?全部内容,希望文章能够帮你解决java – 当存在多个构造函数时,使用autowire =“constructor”进行依赖注入?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。