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

Let consider the following example:

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:

Constructor Injection with overloaded constructors in Spring

with Application class has content as below:

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:

With this declaration, Spring will call the constructor:

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

Result:

Constructor Injection with overloaded constructors in Spring

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

Now, Spring will call the constructor:

to initial Student object and result will be as below:

Constructor Injection with overloaded constructors in Spring

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

 

Reference the project on GitHub: https://github.com/huongdanjavacom/huongdanjava.com/tree/master/spring-overloaded-constructor-injection


Constructor Injection with overloaded constructors in Spring
Đánh giá bài viết
Chia sẽ bài viết này ...Share on Facebook
Facebook
3Tweet about this on Twitter
Twitter
Share on LinkedIn
Linkedin

One thought on “Constructor Injection with overloaded constructors in Spring

Add Comment

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