Link to home
Start Free TrialLog in
Avatar of gudii9
gudii9Flag for United States of America

asked on

setter and constructor injection in spring

I was reading folowing lines and I did not understand clearly.

Alternative to setter injection
Setter injection is a straightforward way to configure, wire bean properties.
But one shortcoming of setter injection is that assumes that all mutable properties
are available via a setter method. You may not want all of your beans to
behave this way. For one thing, when this type of bean is instantiated, none of its
properties have been set and it could possibly be in an invalid state.
 Second, you
may want certain properties to be set just once when the bean is created and
become immutable after that point. This is complicated, if not impossible, when
exposing all properties through setters.
An alternative is to design your beans where some properties are set via constructors.
This is a particularly good design if some properties are required and
immutable, such as a DAO s DataSource.

So if you choose to design some of your
beans this way or are working with beans that are already designed this way, you
still need a way to configure these objects through Spring. use constructor injection to set the minimal properties for
a bean.

Any ideas, resources,sample code,links, highly appreciated. thanks in advance.
Avatar of Mick Barry
Mick Barry
Flag of Australia image

you don't always want to add setters to your bean, for example you may not want a property to be changed.
For spring to inject values into these beans you can use constructor injection instead of using the setter
Avatar of gudii9

ASKER

>>you don't always want to add setters to your bean, for example you may not want a property to be changed.

can you please elaborate on this.
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial