c3p0
c3p0

Reputation: 125

Spring Overloaded Constructor Autowiring

I have a class with overloaded constructors, like this:

@Component
public class MyClass {
    private ClassA myMemberA;
    private ClassA myMemberB;

    @Autowire
    public MyClass(@Qualifier ("qualifierA") ClassA objectA, ClassA objectB) {
       myMemberA = objectA;
       myMemberB = objectB;
    }

    @Autowire
    public MyClass(ClassA objectA) {

       myMemberA = objectA;
    }
}

Basically, one constructor has two arguments of ClassA, and one constructor has just one argument. I have two beans of type ClassA defined. I would like to have one of the two constructors invoked and autowired accordingly depending on the use case.

When I ran this code, I got the error:

Invalid autowire-marked constructor: ...
Found another constructor with 'required' Autowired annotation: ...

Is it possible to have overloaded autowired constructors? If yes, what is the right way to do it?

Thank you!

Upvotes: 4

Views: 5692

Answers (1)

Migsarmiento
Migsarmiento

Reputation: 153

  1. You need to define which constructor Spring will be prioritizing by writing something like this: @Autowired(required=true) or @Autowired(required=false). You are only allowed to have one constructor with @Autowired(required=true). By default, if you don't define the required property, it will be set to true, which is the problem in your case.
  2. I don't see the point of having two Autowired constructors if only one of them will be wired anyway. If you're trying to Autowire the two instances of ClassA, it might be better to add the @Autowired annotation to the setters or the variables.

Upvotes: 3

Related Questions