• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Spring Constructor Injection – Resolving Ambiguity

May 13, 2016 by javainterviewpoint Leave a Comment

In Spring Constructor Injection we will be injecting values to the property using the Constructor available. Whenever you specify the class attribute for a bean, then you are implicitly asking the Spring IoC container to create the bean instance by invoking its constructor.

Folder Structure:

  1. Create a new Java Project  “SpringCoreTutorial” and create a package for our src files “com.javainterviewpoint“
  2. Add the required libraries to the build path. Java Build Path ->Libraries ->Add External JARs and add the below jars.

    commons-logging-1.2.jar
    spring-beans-4.2.4.RELEASE.jar
    spring-core-4.2.4.RELEASE.jar
    spring-context-4.2.4.RELEASE.jar
    spring-expression-4.2.4.RELEASE.jar

  3. Create the Java classes Student.java and StudentLogic.java under  com.javainterviewpoint folder.
  4. Place our configuration file SpringConfig.xml in the src directory

Student.java

Our Student class will have all the student details such name, age, percentage and its corresponding POJO’s. The getStudentDetails() method will display the student information which is set.

package com.javainterviewpoint;

public class Student
{
    private String name;
    private int age;
    private int percentage;
    
    public Student()
    {
        super();
    }
    public Student(String name, int age, int percentage)
    {
        super();
        this.name = name;
        this.age = age;
        this.percentage = percentage;
    }
    
    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public int getAge()
    {
        return age;
    }
    public void setAge(int age)
    {
        this.age = age;
    }
    public int getPercentage()
    {
        return percentage;
    }
    public void setPercentage(int percentage)
    {
        this.percentage = percentage;
    }
    
    public void getStudentDetails()
    {
        System.out.println("**Student Details**");
        System.out.println("Student Name       : "+name);
        System.out.println("Student Age        : "+age);
        System.out.println("Student Percentage : "+percentage);
    }
}

SpringConfig.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

   <bean id="student" class="com.javainterviewpoint.Student">
      <constructor-arg value="JavaInterviewPoint" />
      <constructor-arg value="999" />
      <constructor-arg value="100" />
   </bean>
</beans>
  • SpringConfig.xml has the bean definitions, We have set bean id as “student” for our Student class which will act as the reference for calling our Student class.
  • Using the Spring Constructor Dependency Injection <constructor-arg> tag we are setting the values to the properties of the Student class through the constructor.

Spring IoC Container using BeanFactory

BeanFactory is an interface belonging to org.springframework.beans.factory.BeanFactory. We need to instantiate one of the implementations, here we will be instantiating XmlBeanFactory.

package com.javainterviewpoint;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class StudentLogic
{
    public static void main(String args[])
    {
      //Read the configuration file
        Resource resource = new ClassPathResource("SpringConfig.xml");
        //Read all the bean definition
        BeanFactory bf = new XmlBeanFactory(resource);
        //Get the Student class instance
        Student st = (Student)bf.getBean("student");
        //Print the student details
        st.getStudentDetails();
    }
}
  • In our StudentLogic class we will  Read the Configuration file(SpringConfig.xml) through Resource class
  • Bean Factory will take the resource as input to get all the bean instances.
  • Get the Student Class instance by calling the getBean() method over the bean factory.
  • The String passed to getBean() method should be equivalent to the id defined in the SpringConfig.xml
  • Call the getStudentDetails() method to display the values which we injected through the Spring Constructor Injection.

Output : 

Once we run the StudentLogic class, we will be getting the below output

Constructor Injection

 

 

In the above case we have only one parameterized constructor and hence we didn’t have any ambiguity issues. When we are specifying one or more constructor argument for a bean, Spring IoC Container will try to find appropriate constructor and will try to inject. However when more than one constructor is found matching the argument which we passed it will cause ambiguity in Constructor. Lets make some changes to our Student class.

Student.java

package com.javainterviewpoint;

public class Student
{
    private String name;
    private int age;
    private int percentage;
    
    public Student()
    {
        super();
    }
    public Student(String name, String age)
    {
        super();
        System.out.println("Inside Constructor 1");
        this.name = name;
        this.age = Integer.parseInt(age);
    }
    public Student(String name, int age)
    {
        super();
        System.out.println("Inside Constructor 2");
        this.name = name;
        this.age = age;
    }
    
    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public int getAge()
    {
        return age;
    }
    public void setAge(int age)
    {
        this.age = age;
    }
    public int getPercentage()
    {
        return percentage;
    }
    public void setPercentage(int percentage)
    {
        this.percentage = percentage;
    }
    
    public void getStudentDetails()
    {
        System.out.println("**Student Details**");
        System.out.println("Student Name       : "+name);
        System.out.println("Student Age        : "+age);
        System.out.println("Student Percentage : "+percentage);
    }
}

We will be injecting values like below

 <bean id="student" class="com.javainterviewpoint.Student">
      <constructor-arg value="JavaInterviewPoint" />
      <constructor-arg value="999" />
      <property name="percentage" value="100"/>
   </bean>

Output : 

 Inside Constructor 1
**Student Details**
Student Name : JavaInterviewPoint
Student Age : 999
Student Percentage : 100

Instead of getting into Constructor 2, values got injected through Constructor 1. Spring has considered the value of age as String and injected values through Constructor 1.

Spring Constructor Injection – Resolving Constructor Ambiguity

This ambiguity can be resolved using the type attribute of the <constructor-arg> tag. Lets see Spring Constructor Injection multiple arguments, Now the bean can be written like below.

<bean id="student" class="com.javainterviewpoint.Student">
      <constructor-arg type="java.lang.String" value="JavaInterviewPoint" />
      <constructor-arg type="int" value="999" />
      <property name="percentage" value="100"/>
   </bean>

Now the Constructor 2 will be called correctly as we have added the type attribute and the output will be like below.

Inside Constructor 2
**Student Details**
Student Name : JavaInterviewPoint
Student Age : 999
Student Percentage : 100

This way we can call any parameterized constructor precisely without any ambiguity issues.

Resolving argument order Ambiguity:

If suppose we are having one more parameterized constructor in our Student class.

package com.javainterviewpoint;

public class Student
{
    private String name;
    private int age;
    private int percentage;
    
    public Student()
    {
        super();
    }
    public Student(String name, String age)
    {
        super();
        System.out.println("Inside Constructor 1");
        this.name = name;
        this.age = Integer.parseInt(age);
    }
    public Student(String name, int age)
    {
        super();
        System.out.println("Inside Constructor 2");
        this.name = name;
        this.age = age;
    }
    public Student(int age, String name)
    {
        super();
        System.out.println("Inside Constructor 3");
        this.name = name;
        this.age = age;
    }
    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public int getAge()
    {
        return age;
    }
    public void setAge(int age)
    {
        this.age = age;
    }
    public int getPercentage()
    {
        return percentage;
    }
    public void setPercentage(int percentage)
    {
        this.percentage = percentage;
    }
    
    public void getStudentDetails()
    {
        System.out.println("**Student Details**");
        System.out.println("Student Name       : "+name);
        System.out.println("Student Age        : "+age);
        System.out.println("Student Percentage : "+percentage);
    }
}

Our bean is like below

<bean id="student" class="com.javainterviewpoint.Student">
      <constructor-arg type="int" value="999" />
      <constructor-arg type="java.lang.String" value="JavaInterviewPoint" />
      <property name="percentage" value="100"/>
   </bean>

Here the “Constructor2” will be called instead of “Constructor3” this happens because Spring internally scores the constructor for compatibility with the arguments. Now both the Constructor 2 and Constructor 3 gets the same score. Here the order of argument mentioned in the XML is not considered. Spring IoC Container picks up the first matched constructor and hence the Constructor2 will be called.

To avoid this problem, we can indicate the indexes of the arguments explicitly through the index attribute of <constructor-arg>.

<bean id="student" class="com.javainterviewpoint.Student">
      <constructor-arg type="int" index="0" value="999" />
      <constructor-arg type="java.lang.String" index="1" value="JavaInterviewPoint" />
      <property name="percentage" value="100"/>
   </bean>

Now Constructor3 will be called. Specifying index is not a mandatory one, if you are sure that the constructors will not cause any ambiguity.

Other interesting articles which you may like …

  • Spring 3 Hello World Example
  • Spring 3 JavaConfig Example
  • Spring 3 @Import annotation with JavaConfig Example
  • Dependency Injection In Spring
  • Spring Dependency Injection – Setter Injection
  • Spring Setter Injection With Primitive data types
  • Spring Setter Injection With Objects
  • Spring Dependency Injection With Set Collection Example
  • Spring Dependency Injection With Map Collection Example
  • Spring Dependency Injection With Properties Example
  • Spring Difference between Setter and Constructor Injection

Filed Under: J2EE, Java, Spring, Spring Core, Spring Tutorial Tagged With: Constructor Injection, Resolving ambiguity, Spring, Spring Constructor Injection

Leave a Reply Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·