In the previous tutorial, I introduced you all about Constructor Injection in Spring. But because we can have overloaded constructors in Java, so in this tutorial, will show you all how we can declare those overloaded constructors in Spring container.
Let consider the following example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
package com.huongdanjava.springoverloadedconstructorinjection; public class Student { private String name; private int age; public Student(String name) { this.name = name; } public Student(int age) { this.age = age; } public Student(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return "Student [name=" + name + ", age=" + age + "]"; } } |
As you see, the Student object has 3 constructors, 2 of them is overloaded constructors. Now, we will consider each case!
But first of all, I will create new Maven project:
with Application class has content as below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package com.huongdanjava.springoverloadedconstructorinjection; import org.springframework.beans.factory.BeanFactory; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Application { public static void main(String[] args) { BeanFactory context = new ClassPathXmlApplicationContext("spring.xml"); Student student = (Student) context.getBean("student"); System.out.println(student.toString()); } } |
OK, let’s get started.
With overloaded constructors, we need to specify the data type for each argument in the constructor.
Example, I want to initial Student object with name “Khanh”. I will declare in Spring container as below:
1 2 3 |
<bean id="student" class="com.huongdanjava.springoverloadedconstructorinjection.Student"> <constructor-arg type="java.lang.String" value="Khanh" /> </bean> |
With this declaration, Spring will call the constructor:
1 2 3 |
public Student(String name) { this.name = name; } |
to initial Student object because the data type of name variable is String.
Result:
If now I want to initial Student object with age is 30, then I need to change the data type as below:
1 2 3 |
<bean id="student" class="com.huongdanjava.springoverloadedconstructorinjection.Student"> <constructor-arg type="int" value="30" /> </bean> |
Now, Spring will call the constructor:
1 2 3 |
public Student(int age) { this.age = age; } |
to initial Student object and result will be as below:
With the constructor has many arguments, we declare it as normal:
1 2 3 4 |
<bean id="student" class="com.huongdanjava.springoverloadedconstructorinjection.Student"> <constructor-arg value="Khanh" /> <constructor-arg value="30" /> </bean> |
Reference the project on GitHub: https://github.com/huongdanjavacom/huongdanjava.com/tree/master/spring-overloaded-constructor-injection
faisal
XML based configuration …. yuk!