0% found this document useful (0 votes)
1 views3 pages

Setter Injection

Setter Injection in Spring allows for injecting dependencies into a bean through its setter methods using the <property> tag within the <bean> tag. This method is useful for assigning values to optional or configurable properties, such as primitive types. An example is provided with the Alien class, where the age property is set to 21 via the Spring XML configuration.

Uploaded by

tejaspoche100
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views3 pages

Setter Injection

Setter Injection in Spring allows for injecting dependencies into a bean through its setter methods using the <property> tag within the <bean> tag. This method is useful for assigning values to optional or configurable properties, such as primitive types. An example is provided with the Alien class, where the age property is set to 21 via the Spring XML configuration.

Uploaded by

tejaspoche100
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

05 - Setter Injection

Setter Injection is a way in Spring for injecting dependencies or values into a bean
through its setter methods.

● Inside the <bean> tag, the <property> tag is used to inject values into the
corresponding fields of the bean via its setter methods.
○ name: Refers to the name of the property (variable) in the class.
○ value: Assigns the value to that property.
● The value attribute in the <property> tag is used to inject primitive types
such as int, boolean, String, etc.
● It is commonly used when the bean has optional or configurable properties.

Code:

[Link]

private int age;

public Alien() {

[Link]("Object Created");

public int getAge() {

return age;

public void setAge(int age) { // Setter Injection

[Link]("Setter called");

[Link] = age;

}
public void code() {

[Link]("Coding");

[Link]:

public class Alien {

private int age;

public Alien() {

[Link]("Object Created");

public int getAge() {

return age;

public void setAge(int age) {

[Link]("Setter called");

[Link] = age;

public void code() {

[Link]("Coding");

}
[Link]

<bean id="alien1" class="[Link]" >

<property name="age" value="21"> </property>

</bean>

● The name="age" corresponds to the age variable in the Alien class.


● The value="21" assigns the value 21 to the age variable.

Output:

In this example, When the ApplicationContext loads the XML file, it creates an
object for the Alien class. The setter method setAge(int age) is called, and the
value 21 is passed as an argument.

Code Link:
[Link]
course/tree/c6690e4f2c70d8f530d70623f13d14ff0ffd7e7d/2%20Exploring%20Spri
ng%20Framework/2.5%20Setter%20Injection/Spring1

You might also like