Constructor Injection with overloaded constructors in Spring

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, I will show you all how we can declare those overloaded constructors in the Spring container.

Let’s consider the following example:

As you see, the Student object has 3 constructors, 2 of them are overloaded constructors. Now, we will consider each case!

But first of all, I will create a new Maven project:

Constructor Injection with overloaded constructors in Spring

I will use Java 17 for this example application:

Spring dependency is as follows:

The Application class has the content below:

OK, let’s get started.

With overloaded constructors, we need to specify the data type for each argument in the constructor.

For example, I want to initialize a Student object with the name “Khanh”. I will declare in Spring container as below:

With this declaration, Spring will call the constructor:

to initialize the Student object because the data type of the name variable is String.

Result:

Constructor Injection with overloaded constructors in Spring

If now I want to initialize the Student object with an age is 30, then I need to change the data type as below:

Now, Spring will call the constructor:

to initialize the Student object and the result will be as below:

Constructor Injection with overloaded constructors in Spring

With the constructor has many arguments, we declare it as normal:

One thought on “Constructor Injection with overloaded constructors in Spring

Add Comment