Home » Spring » Constructor Injection In Spring

Constructor Injection In Spring

As the name tells, constructor injection is carried out by constructors of the bean.spring container uses constructor of the bean class for assigning the dependencies.We may have any number of constructors in our bean classes.The constructor will take arguments based on number of dependencies required.For achieving constructor Injection , we need to inform to the spring IOC container about constructor injection by using <constructor-arg=""/> in spring configuration xml file.

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 injection will happen after object creation.

We can inject following types of values by using constructor injection.

  • primitive and String-based values
  • Collection values etc.
  • Dependent object (Bean Reference)

Example of Constructor Injection in Spring

Bean Class

public class HelloBean
{
public string message;
public HelloBean (String message)
{
This.message = message;
}
public void setMessage(String message)
{
This.message = message;
}
public void show()
{
System.out.println("This is Constructor Injection in Spring");
}
}

Configuration XML

Below is the code snippet to use the Set in the spring bean configuration file.

<bean id="hellobean" class="HelloBean">
<constructor-arg value="Welcome to Spring Tutorial"/>
<property name="message" value="Welcome to India"/>
</bean>

When we call factory.getBean("hellobean"), then internally spring framework executes following statements.

HelloBean helloBean = new HelloBean("Welcome to Spring Tutorial");
helloBean.setMessage("Welcome to India");

Output of above program will be Welcome to India, not Welcome to java4s. As we already told constructor will be executed at object creation, so at the time of object creation Welcome to Spring Tutorial will be assigned into message property, then setter will be called so previous value will be overridden and new value is now Welcome to India.


Previous Next Article
comments powered by Disqus