Setter Injection
|
Constructor Injection
|
|
1. In Setter Injection, partial injection of dependencies can
possible, means if we have 3 dependencies like int, string, long, then its
not necessary to inject all values if we use setter injection. If you are not
inject it will takes default values for those primitives
|
1. In constructor injection, partial injection of
dependencies cannot possible, because for calling constructor we must pass
all the arguments right, if not so we may get error
|
|
2. Setter Injection will overrides the constructor injection value,
provided if we write setter and constructor injection for the same property
[i already told regarding this, hope you remember]
|
2. But, constructor injection cannot overrides the setter
injected values
|
|
3. If we have more dependencies for example 15 to 20 are
there in our bean class then, in this case setter injection is not
recommended as we need to write almost 20 setters right, bean length will
increase.
|
3. In this case, Constructor injection is highly recommended,
as we can inject all the dependencies with in 3 to 4 lines [i mean, by
calling one constructor]
|
|
4. Setter injection makes bean class object as mutable [We
can change ]
|
4. Constructor injection makes bean class object as immutable
[We cannot change ]
|
There are many key differences between
constructor injection and setter injection.
- Partial
dependency:
can be injected using setter injection but it is not possible by constructor.
Suppose there are 3 properties in a class, having 3 arg constructor and
setters methods. In such case, if you want to pass information for only
one property, it is possible by setter method only.
- Overriding: Setter
injection overrides the constructor injection. If we use both constructor
and setter injection, IOC container will use the setter injection.
- Changes: We can easily
change the value by setter injection. It doesn't create a new bean
instance always like constructor. So setter injection is flexible than
constructor injection.
No comments:
Post a Comment