Spring Framework Constructor Injection Example

In our introduction to Spring Framework tutorial we discussed the benefits of Spring Framework along with the topics of Inversion of Control and Dependency Injection. In addition, we discussed several different ways we perform dependency injection. That is, we can perform setter injection, constructor injection and method injection.

In this tutorial Spring Construction Injection Example, we will concentrate on Constructor Injection. As the name suggests, constructor injection is form of dependency injection that is accomplished when we supply the arguments to the constructor so that when the bean is instantiated by the factory it contains all of the necessary information to be property constructed.

Let’s look at our Client class for some basics.

Client Class (Client.java)

package com.avaldes;

public class Client {
  private int id;
  private String name;
  private String email;
  private boolean active;
  
  public Client() {}

  public Client(int id) {
    this.id = id;
  }
  
  public Client(String name) {
    this.name = name;
  }

  public Client(boolean active) {
    this.active = active;
  }

  public Client(int id, String name, String email, boolean active) {
    this.id = id;
    this.name = name;
    this.email = email;
    this.active = active;
  }
  
  @Override
  public String toString() {
    return "Client [id=" + id 
                  + ", name=" + name 
                  + ", email=" + email 
                  + ", active=" + active + "]";
  }
}

Spring Constructor Injection (Default String Type)

By default, if we do not specify the type associated with the constructor argument it will default to a string type. So, in this case, we will call the constructor Client(String name).

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:p="http://www.springframework.org/schema/p"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
 
  <bean id="client1" class="com.avaldes.Client">
    <constructor-arg value="Amaury Valdes"></constructor-arg>  
  </bean>
</beans>

Output – Default

Output: Client [id=0, name=Amaury Valdes, email=null, active=false]

Spring Constructor Injection – A Case of Mistaken Identity (Type)

When using constructor injection it sometimes becomes important to ensure that the type is defined as leaving it out can result in the wrong constructor getting called. In this case, we wanted to set the ID to an integer value of 123, but since we did not specify a type Spring used the default setting of type=java.lang.String and set the name to 123 instead of the id.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:p="http://www.springframework.org/schema/p"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
 
  <bean id="client1" class="com.avaldes.Client">
    <constructor-arg value="123"></constructor-arg>  
  </bean>
</beans>

Output – Incorrect Constructor was called

Output: Client [id=0, name=123, email=null, active=false]

Spring Constructor Injection – Name Attribute

In order to avoid such ambiguity Spring provides the name attribute which will help you identify each constructor argument name and make it much easier to associate it to the correct constructor.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:p="http://www.springframework.org/schema/p"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
 
  <bean id="client" class="com.avaldes.Client">
    <constructor-arg name="id" value="678"></constructor-arg>  
    <constructor-arg name="email" value="Jane Doe"></constructor-arg>
    <constructor-arg name="name" value="jane@doe.com"></constructor-arg>
    <constructor-arg name="active" type="boolean" value="true"></constructor-arg>  
  </bean>
</beans>

Output – Name Attribute

Client [id=678, name=jane@doe.com, email=Jane Doe, active=true]

Constructor Injection – Type Attribute

Another way to avoid such ambiguity is by using the type attribute which will help you identify each constructor argument type and make it much easier to associate it to the correct constructor.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:p="http://www.springframework.org/schema/p"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
 
  <bean id="client" class="com.avaldes.Client">
    <constructor-arg type="int" value="567"></constructor-arg>  
    <constructor-arg type="java.lang.String" value="Amaury Valdes"></constructor-arg>
    <constructor-arg type="java.lang.String" value="amaury.valdes@mail.com"></constructor-arg>
    <constructor-arg type="boolean" value="true"></constructor-arg>  
  </bean>
</beans>

Output – Type Attribute

Output: Client [id=567, name=Amaury Valdes, email=amaury.valdes@mail.com, active=true]

Spring Constructor Injection – Index Attribute

Another option we have at our disposal is the index attribute which will help you identity the argument based on the ordinal position of the in the constructor.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:p="http://www.springframework.org/schema/p"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
 
  <bean id="client" class="com.avaldes.Client">
    <constructor-arg index="0" value="567"></constructor-arg>  
    <constructor-arg index="1" value="John Smith"></constructor-arg>
    <constructor-arg index="2" value="john@smith.com"></constructor-arg>
    <constructor-arg index="3" value="true"></constructor-arg>  
  </bean>
</beans>

Output – Index Attribute

Output: Client [id=567, name=John Smith, email=john@smith.com, active=true]

That’s It

As a general rule, you should try to use the optional name, index or type attributes with constructor arguments. Although these attributes are optional, using them will help avoid ambiguity which may lead to errors and unexpected results.

spring framework

Related Posts

  • Introduction to Spring Framework, IoC and Injection
    In this tutorial we will cover a basic introduction the Spring framework, Inversion of Control and Dependency Injection. We will discuss the benefits of using it, and why it is so popular in today's environment.
  • Spring Framework Constructor Injection Example
    In this tutorial, we will concentrate on Constructor Injection. As the name suggests, constructor injection is form of dependency injection that is accomplished when we supply the arguments to the constructor so that when the bean is instantiated by the factory it contains all of the necessary information to be property constructed.
  • Spring Framework Constructor Injection with Collections Example
    In this tutorial, we will modify our previous example and add a few collections so we can illustrate how we use constructor injection with differing collection types. Specifically, we will show how to perform constructor injection with List, Map and Set objects.
  • Spring Framework Setter Injection with Examples
    In this tutorial we will discuss Spring Framework Setter Injection which is the main method of dependency injection in Spring. The property element is used to define the setter injection in Spring by using the name of the property element and looking for the corresponding setXXXXXX methods in the specified bean.
  • Spring Bean Scopes Example
    In this tutorial we will begin covering scope of Spring beans. In Spring when you define a bean in the Spring configuration file, you are telling Spring about its scope whether you define it or not. This is a powerful and flexible approach because you can choose the scope of the objects you create via configuration instead of having to hardcode the scope of an object at the Java class level.
  • Spring Bean Life Cycle Example – @PostConstruct, @PreDestroy, InitializingBean, DisposableBean, init-method and destroy-method
    In this tutorial we will cover the Spring Bean Life Cycle and the methods, attributes and annotations used to hook into the management of the bean life cycle in the IoC container.
  • Integrating Java JMX Managed Beans using Spring and Annotations
    This post will show how to create managed beans using the JMX standard using Spring. JMX stands for Java Management Extensions, and was created to implement a standard and uniform way to manage your applications. By using JMX remote can connection to a JVM and monitor running applications on that JVM. In addition to monitoring, remote clients are able to directly run methods and modify runtime parameters of the application that is being managed.
  • Integrating Spring Message Driven POJO with ActiveMQ
    This post will show how to create a message driven POJO that can send and receive JMS message using ActiveMQ as the Message Oriented Middleware (MOM). We will discuss various approaches to creating the MDPs (Message Driven POJOs) in this tutorial and discuss setting up ActiveMQ from Apache.

Please Share Us on Social Media

Facebooktwitterredditpinterestlinkedinmail

Leave a Reply

Your email address will not be published. Required fields are marked *