Reputation: 125
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
Reputation: 153
@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.ClassA
, it might be better to add the @Autowired
annotation to the setters or the variables. Upvotes: 3