Module 1: Spring Dependency Injection - dineshmadhup/Spring GitHub Wiki

Spring Dependency Injection

How EmployeeService can be injected in Manager using Dependency Injection (Constructor Injection Type)?

Lets follow the steps to do this:

Configuration of Spring Container

The primary function of configuring spring container is
- To create and manage objects (Inversion of Control)
- To inject object’s dependencies (dependency injection)

There are 3 ways of configuring Spring Container:

  1. XML configuration file
  2. Java Annotation
  3. Java Source Code

Steps to develop Spring:

  1. Configure Spring Beans
  2. Create a Spring Container
  3. Retrieve a beans from Spring Container

XML configuration file

Steps:

XML Configuration File: applicationContext.xml

Step 1: Configure Spring Beans

applicationContext.xml

 <beans ...>
 <bean id="myTeam"   	
      class="com.branch.springwork.MarkettingTeam">    	
 </bean>
 </beans>

Here com.branch.springwork.MarkettingTeam is the fully qualified name of implementation class named MarkettingTeam.

Step 2: Create a Spring Container

Spring container is generally known as ApplicationContext.

 ClassPathXmlApplicationContext context =
              new ClassPathXmlApplicationContext("applicationContext.xml");

Step 3: Retrieve a beans from Spring Container

  // create a spring container
  ClassPathXmlApplicationContext context = 
           new ClassPathXmlApplicationContext("applicationContext.xml");

 // retrieve beans from spring container
 Manager manager = context.getBean("myTeam**", Manager.class);

 In applicationContext.xml file:
              <bean id="myTeam"
                    class=“com.branch.springwork.MarkettingTeam">

myTeam is bean id in which should match with configuration file (applicationContext.xml).
Manager.class is interface which is implemented in MarkettingTeam

Dependency Injection: In this project I have used Constructor injection

How Spring Framework process the config File:

In applicationContext.xml file, we have following lines of bean id code and constructor injection

  <bean id="myService"
	      class="com.branch.springwork.MyEmployeeService" />
  <bean id="myTeam"
	      class=“com.branch.springwork.MarkettingTeam”>
<constructor-arg ref="myService" />

With the reference of above bean id, what Spring Framework creates behind the scene is:

 EmployeeService myService = new MyEmployeeService()
 Manager myteam = new MarkettingTeam(myService)
⚠️ **GitHub.com Fallback** ⚠️