Skip to content
Advertisement

Why the constructor is invoked?

I am new to Spring. Recently I encountered something weird, I was using @Autowired for Auto Injecting Name, Emotion in Person class(I have a different class for each Name, Emotion, Person). I encountered that the Person constructor was getting invoked even if I have not used @Autowired with it. Can anyone explain to me why this is happening?.

Is it related to the Automatic Invocation of Constructor after Object Creation(Person)? Also why Constructor is invoked before @Autowired Functions? (As u can see in the output)

config.xml

JavaScript

Emotion.java

JavaScript

Name.java

JavaScript

Person.java

JavaScript

Main App.java

JavaScript

Output

JavaScript

Advertisement

Answer

You defined a Bean of Person class in your xml file, therefore Spring will create an instance of this class. And the constructor you have defined takes a Name and Emotion both other classes you have an instance of. So Spring will create a Bean of Person even if you don’t use it with Autowire.

And it gets invoked before the ‘@Autowire functions’ as you called them because they are methods and you need an instance to call them and the constructor gets called when you create an instance.

I hope I understood your question correct and this answers it.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement