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:

  • applicationContext.xml

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.


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.

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


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.


ID:0 Name:20

You may also pass the string literal as following:


ID:0 Name:Smith

You may pass integer literal and string both as following:


ID:20 Name:Smith

Leave a Reply

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