本文介绍了用autowire =“构造函数"进行依赖注入.什么时候有多个构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有带有以下构造函数的文本编辑器类

I have text editor class with below constructors

 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>

我观察到的是带有两个参数的构造函数被一致地称为.它是随机的吗?不应该 弹簧抛出异常,因为它不知道需要调用哪个构造函数?

what i observe is constructor with two arguments is called consistently. Is it random? Should not spring throw exception becoz it does not know which constructor needs to be called?

推荐答案

这是Spring如何自动构造构造函数的结果.

This is a consequence of how Spring autowires constructors.

首先要做的是获取所有bean类的构造函数并对其进行排序,首先将公共构造函数的参数数量减少,然后再将所有非公共构造函数的参数数量减少.这些是候选构造函数.

The first thing it does is gets all the bean class' constructors and sorts them, putting public constructors first with decreasing amount of arguments, then all non-public constructors again with decreasing amount of arguments. These are the candidate constructors.

然后遍历这些候选项,尝试从BeanFactory生成参数.如果不能因为缺少Bean或其他原因而无法跳过,则跳过候选者.如果成功找到参数,它将根据许多因素(参数列表长度,参数类型与参数的接近程度等)为当前候选构造函数赋予权重.然后,它会检查前一个候选人的体重,并在一个人比另一个人更好的情况下交换他们的体重.

It then iterates through these candidates, trying to generate the arguments from the BeanFactory. If it can't because a bean is missing or for whatever other reason, it skips the candidate. If it succeeds in finding the arguments, it gives the current candidate constructor a weight based on a number of factors (argument list length, how close the types of the arguments vs the parameters are, etc.). It then checks the previous candidate's weight and swaps them if one is better than the other.

如果此过程结束时有候选构造函数,则Spring将使用它.

If there is a candidate constructor at the end of this process, Spring uses it.

如果您说Spring在3 arg构造函数上使用了2 arg构造函数,那么这意味着您在3 arg构造函数中没有类型之一的bean.

If you're saying that Spring is using your 2 arg constructor over your 3 arg constructor, then that means you don't have a bean of one of the types in your 3 arg constructor.

这篇关于用autowire =“构造函数"进行依赖注入.什么时候有多个构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 15:00