Reputation: 8006
I wanted to see when does setter injection actually happen in Spring, and debugged my code for that. It seems as both constructor and setter injections happen when the first line is executing. I am wondering, if the Service that's going to have that dependency injected will notice the difference at all? In my understanding it won't? If not, then where does the difference lie then?
ApplicationContext context = new ClassPathXmlApplicationContext("spring-module.xml");
//Both setting and constructor dependencies are initialized at this point.
CampaignManager cm = (CampaignManager) context.getBean("campaignManager");
Upvotes: 0
Views: 1325
Reputation: 62874
There are several differences between constructor and setter injection.
Setter injection does not ensure that the injection has happened when the object is created. You cannot guarantee that a certain injection has occured, e.g. there may be an object with incomplete dependency, while the constructor injection doesn't allow objects to be created before their dependencies are created.
If there is a circular dependency between two beans (for example, A
depends on B
and B
depends on A
) Spring will throw a ObjectCurrentlyInCreationException
when using constructor injection, while when using setter injection Spring will create both of the beans before the setter method are invoked.
Use constructor injection when the bean has to be created will all of it's dependencies.
Use setter injection when the number of dependencies is huge.
More info:
Upvotes: 2