Module 1: Spring Dependency Injection - dineshmadhup/Spring GitHub Wiki
How EmployeeService can be injected in Manager using Dependency Injection (Constructor Injection Type)?
Lets follow the steps to do this:
The primary function of configuring spring container is
- To create and manage objects (Inversion of Control)
- To inject object’s dependencies (dependency injection)
- XML configuration file
- Java Annotation
- Java Source Code
- Configure Spring Beans
- Create a Spring Container
- Retrieve a beans from Spring Container
Steps:
XML Configuration File: applicationContext.xml
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.
Spring container is generally known as ApplicationContext.
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext.xml");
// 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
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)