[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 349
  • Last Modified:

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.
0
gudii9
Asked:
gudii9
  • 2
1 Solution
 
objectsCommented:
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
0
 
gudii9Author Commented:
>>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.
0
 
objectsCommented:
some properties should not be changed, for example an id.
in these cases you don't want to have a setter for that property (as it would allow the property to be changed)
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now