Dependency injection by Constructor in Spring Container:

Dependency injection by Constructor in Spring Container:
  • We can inject the dependency by constructor in spring framework, use the <constructor-arg> sub tag of <beans> tag in the bean configuration file and supply the values.
  • If the constructor parameter type is simple type, to supply value we can use “value” attribute. 
  • If the constructor parameter type is Object type, to supply value we can use “ref” attribute.
  • Let’s see the sample example to inject sample (primitive and standard based values) and reference (object) type values. Follow the below steps for Constructor dependency injection (DI).
Step-1: Project Structure.
Step-2: Create Spring Bean class with the required dependencies.
Step-3: Define the parameterized constructor to support for constructor DI.
Step-4: Use the <constructor-arg> tag in bean configuration file.
Step-5: Get the bean object from beans configuration file in Client app.
Step-6: Required jar/dependency configuration in pom.xml file.
Step-7: Output of Application

Step-1: Project Structure.


Step-2: Create Spring Bean class with the required dependencies:
Creating a Department.java class with required fields, in this example I have created with 3 fields, ie., deptNo, deptName and deptDesc, all are String data type.

Step-3: Define the parameterized constructor to support for constructor DI:
Creating a Employee.java class with required fields and with 2 constructors like below

Step-4: Use the <constructor-arg> tag in bean configuration file:
Below is the beans configuration file, provided by spring framework, we need to configure all the bean object information in this file as per the spring API. In the below file we configured Employee and Department object information, and getting this object in TestApp.java class by using bean class name.

Step-5: Get the bean object from beans configuration file in Client app:
TestApp.java class is a main method class and getting bean objects using bean name in my-beans.xml file configuration with the help of ApplicationContext object provided by spring framework.
In this example we are getting two types of objects from beans configuration file. One object is Employee object and another object also Employee object with Department object. (Department object is available in Employee object as per the Employee.java class declaration.)

Step-6: Required jar/dependency configuration in pom.xml file:
Configured required spring dependencies/jar information in pom.xml file

Step-7: Output of Application:


Dependency injection by Constructor in Spring Container: Dependency injection by Constructor in Spring Container: Reviewed by Gurugubelli Technologies on December 31, 2017 Rating: 5

No comments:

Powered by Blogger.