Spring Dependency Injection via Constructor

Spring Dependency Injection via Constructor

The below example describes Spring Dependency Injection via Constructor which is one of the Dependency Injection Method.

Use Case

Lets consider we have an Application where in we need to format various types of Payload such as JSON, XML, ATOM etc. Keeping this in mind lets develop an Helper Class which with help of various Formatters creates a Formatted Output.

1. Project Setup

Lets create a Spring Maven Project with the below pom.xml

2. Code Interface

Code an Interface for the Formatter as

3. Code Implementation

add an JSON Formatter Implementation for the above Interface

4. Code a Helper Class

This is the class to which the above JSON Formatter is Injected via Setter

5. Configure Spring & Declare Bean

Define the Beans and the Helper Class in applicationContext.xml as below

6. Main Program

The main program to test Di via Constructor would be

7. Output:

Output

Output

8. Project Structure:

DI_Constructor

 

Download-Spring-Maven-Project

I hope this has been useful for you and I’d like to thank you for reading. If you like this article, please leave a helpful comment and share it with your friends.

Leave a Reply

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