Sanjaykumar A
Sanjaykumar A

Reputation: 43

Performing both setter and constructor injection

I am new to spring framework. I tried to inject dependency with both the injection methods(Setter and constructor). I was expecting the output defined in setter injection as it is overridden against constructor injection. But, I have received error message like

Bean creation exception:No default constructor found

If we apply both the injection methods,will it throw error?

Upvotes: 2

Views: 1132

Answers (1)

davidxxx
davidxxx

Reputation: 131346

I tried to inject dependency with both the injection methods(Setter and constructor).

You should be able to do that. According to the Spring version, the result may differ but I can confirm that it works with the Spring 5 version.

Your error :

Bean creation exception:No default constructor found.

makes think that the constructor with the argument is not considered by Spring as a way to autowire your bean.
In old Spring versions (3 and less and maybe 4 I didn't remember), you have to specify @Autowired in the constructor to make Spring aware of it.
So you should declare :

@Autowired
public void setMyDep(MyDep myDep) {
    this.myDep = myDep;
}

@Autowired
public FooBean(MyOtherDep myOtherDep) {
    this.myOtherDep = myOtherDep;
}

In recent Spring versions, declaring @Autowired is not required any longer :

@Autowired
public void setMyDep(MyDep myDep) {
    this.myDep = myDep;
}

public FooBean(MyOtherDep myOtherDep) {
    this.myOtherDep = myOtherDep;
}

Upvotes: 1

Related Questions