1

Kindly let help to understand in which scenario I should user constructor injection and setter injection. Please help me with appropriate Example.

Thanks in advance.

2 Answers 2

3

We usually advise people to use constructor injection for all mandatory collaborators and setter injection for all other properties. Again, constructor injection ensures all mandatory properties have been satisfied, and it is simply not possible to instantiate an object in an invalid state (not having passed its collaborators). In other words, when using constructor injection you do not have to use a dedicated mechanism to ensure required properties are set (other than normal Java mechanisms).

More details http://blog.springsource.org/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/

Sign up to request clarification or add additional context in comments.

1 Comment

Iv seen that explanation before and still cannot get the idea behind this. What is mandatory collaborator here? If Ill try to inject nonexisting bean on field/constructor/setter, initialization will fail anyway. So how could I NOT SATISFY required dependencies?(besides passing null as ctor arg)
3

Personally, I tend towards constructor injection, and I do it for one primary reason.

Immutability.

With immutable objects, it is easier to make code thread safe. This is especially important when dealing with Spring singleton scope objects. If they are mutable, and accessed in different threads, it is not safe to change any of the shared state.

There are other reasons that immutability is beneficial, but I will let a webpage go on about that.

1 Comment

you are right the key point is Immutability. Many of the Spring users should know how GC is effected when not using immutable objects.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.