Newsletter |
Constructor Injection In Spring [ Full Concept ]
In this type of injection spring container uses constructor of the bean class for assigning the dependencies. In spring config xml, we need to inform to the spring IOC container about constructor injection by using <constructor –arg />
In spring bean class, if both constructor and setter injection applied for same property then constructor injection will be overridden by setter injection, because constructor injection will happen at the object creation time, and setter after objection right…, so setter will overrides
For Example:
public class DemoBean { public string message; public DemoBean (String message) { This.message = message; } public void setMessage(String message) { This.message = message; } public void show() { System.out.println("some logic here"); } }
In Config XML
<bean id="id1" class="DemoBean"> <constructor-arg value="Welcome to java4s" /> <property name="message" value="Welcome to spring" /> </bean>
Output
In client application, when we call factory.getBean(“id1”), then internally spring framework executes following statements
DemoBean ob = new DemoBean("Welcome to java4s"); Ob.setMessage("Welcome to spring");
finally value in message will be Welcome to spring, not Welcome to java4s, as setter will over rides constructor, the reason being see i have taken primitive value [string] as dependency, we have written injection for this property in constructor and setter method. We all know constructor will be executed at object creation, so at the time of object creation only some value will be assigned into message property, then setter will be called so previous value will be overrides
———————————– # ———————————
In constructor injection, if argument types are different, then at the time of configuring of xml file we can use type attribute
Example..
public class DemoBean { public int id; public String sname; public DemoBean(int id, string sname) { This.id = id; This.sname = sname; } }
In Config XML
<bean id="id1" class="DemoBean"> <constructor-arg type="java.lang.string" value="1000" /> <constructor-arg value="10" /> </bean>
According to above xml, DemoBean object will be created with 10 as id and 1000 as string [sname]
———————————– # ———————————
Let if we have 2 properties of same type, like user name and password
Example..
public class DemoBean { public String uname, password; public DemoBean (String uname, String password) { This.uname = uname; This.password = password; } }
In our xml
<bean id="id1" class="DemoBean"> <constructor-arg value="myuserName" index="0" /> <constructor-arg value="mypassword" index="1" /> </bean>
Now bean object will be created with myuserName as username, and mypassword as password
———————————– # ———————————
Dependency in the form of object
Let us see how to work with dependency in the form of objects in this constructor injection…
public class DemoBean { public SampleBean sb; public DemoBean(SampleBean sb) { This.sb = sb; } }
In the xml
<bean id="id1" class="DemoBean"> <constructor-arg ref="sb" /> </bean> <bean id="sb" class="SampleBean" />
Note: Here see, directly i given ref as an attribute, so internally it meas ref-bean only not ref-local or ref-parent
———————————– # ———————————
If we have multiple constructors then..
public class DemoBean { public String uname, password; public DemoBean (int id, String uname) { This.id = id; This.uname = uname; } public DemoBean (string uname, int id) { This.id = id; This.uname = uname; } }
XML file will be
<beans> <bean id="id1" class="DemoBean"> <constructor-arg value="10" /> <constructor-arg value="MyUserName" type="java.lang.string"/> </bean> <bean id="id2" class="DemoBean"> <constructor-arg value="MyUserName" /> <constructor-arg value="10" /> </bean> </beans>
In the above example, when we class factory.getBean(“id1“) from client application then spring framework creates an object of DemoBean by calling 1st constructure
If we call factory.getBean(“id2“) then spring framework crates the object of DemoBean by calling 2nd constructor automatically
This is total about this constructor injection in Spring, nothing more than that.
So mates, i don’t think you need any example program on this 🙂
You Might Also Like
::. About the Author .:: | ||
it is very useful to me in many situtions.ThankQ
ohhh great example thank u very much
The best Spring tutorial:) Thanks to java4s.com team 🙂
An Excellent tutorial very nice
Hi.!
Whoever u ppl r, now u r my lovable guruji.! 🙂 I am addicted to ur teaching guruji.!
I found a small mistake here.! in xml mapping file, while mentioning type of constructor argument, u spelled string as “s” in smaller case., it should be java.lang.String.. Its not a big mistake., but somebody will get trouble while attempting to copy paste code from here and try to run.!
Keep going java4s.! Pleasure to learn here.!
Thank you so much!! awesome tutorial indeed 🙂
Nice Explanation 🙂 Thanks Java4s Team I Am Very Pleasure To Learn Here
Its WOwwwww
no doubt good tutorial… but horrible english… and lot of editing need to be done..
Very nice explaination.
Thanks for the nice tutorial
In config file, instead of java.lang.string, it should be java.lang.String
Be frank I am learning Spring in multiple sites but I feel you are best. Good job ! Please include some more concepts in Spring like AOP blah blah..
Hi,
Nice explanation, can you give one example on Spring transaction Module with Simple examples.
Thanks in Advance!.
Sai
hi…
this website was soo good… Thank u…
can i ask u doudt??
in constructor injection, u define xml file like
for calling the Constructor
public DemoBean (string uname, int id)
{
This.id = id;
This.uname = uname;
}
how it will recognize myusername as String and 10 as int…
i mean when we call the constructor it may call this also
public DemoBean (int id, String uname)
{
This.id = id;
This.uname = uname;
}
can anyone plz explain???
Sir,Really Your all the Examples related to all the technology……is Excilent ,marvolous explanation …..u r great sir.
To be frank the way you explained the Constructor Injection is excellent
please explain the scenario with default constructor
To be frank the way you explained the Constructor Injection is excellent
Hi!
on the above example and the sample below the text “If we have multiple constructors then..”
in the multiple constructor ther is no “This.id = id;” global variable found for id.
Hi,
I followed your tutorial it is really very good for beginners.
Please explain thoroughly Bean Life Cycle by taking some easy examples & also explain use of Bean Post Processor.
Can we invoke default constructors by Spring IOC Container.
Please if possible then reply me the way to achieve
eg
class Employee {
private int id;
private String name;
Employee() {} // How to call it by Spring container
public Employee(int id) {
this.id=id;
}
public Employee(String name) {
this.name=name;
}
public Employee(int id, String name) {
this.id=id;
this.name=name;
}
public void show() {
System.out.println(id+" "+name);
}
}
Hi mohd,
If Ur create zero Param constructor in Ur class at the time of object creation spring will use.It means whenever we calling getBean(id) using factory bean object container look into specified class has any zero Param constructor available or not,if not available it will create runtime,if u have still doubt just put private constructor and write one sop in constructor,call above getBean(id) see the console spring never inject in Ur class have any private constructor
A best hands on tut guide keep going on!!!!!!!
I think for second constructor also type should be declared…
let me know if I am wrong
<beans>
<bean id="id1" class="DemoBean">
<constructor-arg value="10" />
<constructor-arg value="MyUserName" type="java.lang.string"/>
</bean>
<bean id="id2" class="DemoBean">
<constructor-arg value="MyUserName" type="?……..?" />
<constructor-arg value="10" />
</bean>
</beans>
Thank you so much for your explanation
I read somewhere sometime that a picture is worth a thousand words now after going through your website i seems to me like your webpage is worth than a 1000 pics…