Newsletter

Constructor Injection In Spring [ Full Concept ]

Spring » on Aug 15, 2011 { 26 Comments } By Sivateja

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 <constructorarg />

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 .::

Java4s_Author
Sivateja Kandula - Java/J2EE Full Stack Developer
Founder of Java4s - Get It Yourself, A popular Java/J2EE Programming Blog, Love Java and UI frameworks.
You can sign-up for the Email Newsletter for your daily dose of Java tutorials.

Comments

26 Responses to “Constructor Injection In Spring [ Full Concept ]”
  1. Manjesh says:

    it is very useful to me in many situtions.ThankQ

  2. praveen says:

    ohhh great example thank u very much

  3. The best Spring tutorial:) Thanks to java4s.com team 🙂

  4. krishna says:

    An Excellent tutorial very nice

  5. 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.!

  6. Amreen says:

    Thank you so much!! awesome tutorial indeed 🙂

  7. Ananth says:

    Nice Explanation 🙂 Thanks Java4s Team I Am Very Pleasure To Learn Here

  8. Nandu says:

    Its WOwwwww

  9. abhinav says:

    no doubt good tutorial… but horrible english… and lot of editing need to be done..

  10. Ranjana says:

    Very nice explaination.

  11. Harshit says:

    Thanks for the nice tutorial

    In config file, instead of java.lang.string, it should be java.lang.String

  12. sureshkumaran says:

    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..

  13. Sai Kommu says:

    Hi,

    Nice explanation, can you give one example on Spring transaction Module with Simple examples.

    Thanks in Advance!.

    Sai

  14. leelavathi says:

    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???

  15. Sir,Really Your all the Examples related to all the technology……is Excilent ,marvolous explanation …..u r great sir.

  16. praveena says:

    To be frank the way you explained the Constructor Injection is excellent

  17. charmila says:

    please explain the scenario with default constructor

  18. To be frank the way you explained the Constructor Injection is excellent

  19. Raj says:

    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.

  20. Shruti says:

    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.

  21. Mohd Islam says:

    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);
    }
    }

    • Narasimha says:

      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

  22. Sanjay says:

    A best hands on tut guide keep going on!!!!!!!

  23. Raj Kumar says:

    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>

  24. saikiran says:

    Thank you so much for your explanation

  25. Jameel Badshah says:

    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…

Name*
Mail*
Website



By posting your answer, you agree to our comments policy.
Most Recent Posts from Top Categories
Spring Boot Hibernate Spring
Contact | About Us | Privacy Policy | Advertise With Us

© 2010 - 2024 Java4s - Get It Yourself.
The content is copyrighted to Sivateja Kandula and may not be reproduced on other websites.