This article will explore a specific type of DI technique called Constructor-Based Dependency Injection within Spring. We can inject the dependency by constructor.The constructor-arg subelement of bean is used for constructor injection.

Let’s see the simple example to learn how to set a bean property via constructor injection. We have created three files here:

  • Students.java
  • applicationContext.xml
  • Test.java
Students.java

The Students bean class has two attributes like id, and name. All the two attributes are set thru constructor injection. The show() method of the Students bean class is overridden to display the user object.

applicationContext.xml

We are providing the information into the bean by this file. The constructor-arg element invokes the constructor. In such case, parameterized constructor of int type will be invoked. The value attribute of constructor-arg element will assign the specified value. The type attribute specifies that int parameter constructor will be invoked.

Test.java

This class gets the bean from the applicationContext.xml file and calls the show method.

Output

ID:10 Name:null

Injecting string-based values

If you don’t specify the type attribute in the constructor-arg element, by default string type constructor will be invoked and the output will be 0 20.

Output

ID:0 Name:20

You may also pass the string literal as following:

Output

ID:0 Name:Smith

You may pass integer literal and string both as following:

Output

ID:20 Name:Smith
It's good to share...Share on FacebookTweet about this on TwitterShare on LinkedInPin on PinterestShare on Google+Email this to someone

Leave a Reply

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