0

I would like to ask about the Spring Constructor Injection. So in the class, I have two constructors with different number of arguments.

public class MyClassHello() {
    public MyClassHello(String A) {
        // do sth
    }

    public MyClassHello(String A, int B){
        // do sth
    }
}

If I try to inject like this to access the 1st constructor, Spring can not work since there is ambiguity.

<bean id="injectQuestion" class="MyClassHello">
    <constructor-arg index="0" value="A String"/>
</bean>

The debug code is like this:

Unsatisfied dependency expressed through constructor argument with index 1 of type [java.lang.String]: Ambiguous constructor argument types.

I think it means, Spring needs to know if the index 1 argument exists?

It is not like the usual case where we have two constructors with same number of arguments. Like that, I could set the type in order to distinguish when injecting.

In my case, is there anyway to force Spring to choose the first constructor?

Thanks a lot!!

Kuhess
  • 2,571
  • 1
  • 18
  • 17
user2152814
  • 257
  • 1
  • 7
  • 17
  • 1
    While I find this odd that your current setup will cause any ambiguity, add a `type` attribute to your constructor definition to clear up any remaining ambiguity. You should then have `` – kolossus Sep 17 '14 at 17:21
  • @kolossus That won't help, I already tried but still the same result. For both constructor the 1st argument is a string. The problem I think is how the injection know whether the 2nd argument exists. – user2152814 Sep 17 '14 at 18:46

1 Answers1

0

You can use the name:

<bean id= "InjectQuestion" class = "MyClassHello">
    <constructor-arg name = "A" value="A String"/>
</bean>

<bean id= "InjectQuestion" class = "MyClassHello">
    <constructor-arg name = "A" value="A String"/>
    <constructor-arg name = "B" value="42"/>
</bean>

Note that your syntax in declaring the class is not valid; and also when defining the bean, in class="..." you should use the fully qualified name of the class (for example packageName.subPackage.MyClassHello not just MyClassHello)

Random42
  • 8,989
  • 6
  • 55
  • 86