What is Dependency Injection?
Dependency injection is a pattern we can use to implement Inversion of control (IOC), where the control being inverted is setting an object's dependencies. Connecting objects with other objects, or “injecting” objects into other objects
Before moving further to the Dependency Injection please check the Inversion of control(IOC)
So for some real motivation let's work on the idea of Dependency Injection
Scenario:
Suppose There is a boy Ravi who wants to learn some outdoor games and he has hired some personal coaches and these coaches gives you the daily workout like Basketball coach gives you some workout so that you can work on your basketball playing skills ,Tennis coach gives you some workout so that you can work on your tennis skills like these cases there are some other coaches also.
In the above scenario we are adding a Fortune Teller to provide the daily fortune
Now to implement this scenario in java programming we have to create some classes and interfaces so
We will create Four classes and Two interfaces
MySelf.java It will be our main class this class will represent Ravi(Who will get the daily workout from a coach)
BaseballCoach.java This class will represent the basketball coach
Coach.java This is an interface so that the similar behaviors of all the coaches can be implemented directly
TennisCoach.java This class will represent the tennis coach
HappyFortuneService.java This is an interface so that the similar behaviors of all the coaches can be implemented directly
FortuneService.java This class will give the daily fortune
Environment setup:
Download the Spring framework click here
Unzip the downloaded Spring framework
Go to project structure in the current project
Click on libraries and then '+' icon
Pass the lib folder from the unzipped folder
And hit enter
Create a file named applicationContext.xml and then past this XML code in the applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- Define your beans here -->
<!-- define the dependency -->
<bean id="myFortuneService"
class="com.luv2code.springdemo.HappyFortuneService">
</bean>
<bean id="myCoach"
class="com.luv2code.springdemo.TrackCoach">
<!-- set up constructor injection -->
<constructor-arg ref="myFortuneService" />
</bean>
</beans>
copy this file and paste it to the src folder
To understand the functionality of the above XML code see the below image
Program :
BaseballCoach.java
public class BaseballCoach implements Coach {
// define a private field for the dependency
private FortuneService fortuneService;
// define a constructor for dependency injection
public BaseballCoach(FortuneService theFortuneService) {
fortuneService = theFortuneService;
}
@Override
public String getDailyWorkout() {
return "Spend 30 minutes on batting practice";
}
@Override
public String getDailyFortune() {
// use my fortuneService to get a fortune
return fortuneService.getFortune();
}
}
Coach.java
public interface Coach {
public String getDailyWorkout();
public String getDailyFortune();
}
FortuneService.java
public interface FortuneService {
public String getFortune();
}
HappyFortuneService.java
public class HappyFortuneService implements FortuneService {
@Override
public String getFortune() {
return "Today is your lucky day!";
}
}
MySelf.java
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MySelf{
public static void main(String[] args) {
// load the spring configuration file
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext.xml");
// retrieve bean from spring container
Coach theCoach = context.getBean("myCoach", Coach.class);
// call methods on the bean
System.out.println(theCoach.getDailyWorkout());
// let's call our new method for fortunes
System.out.println(theCoach.getDailyFortune());
// close the context
context.close();
}
}
TrackCoach.java
public class TrackCoach implements Coach {
private FortuneService fortuneService;
public TrackCoach() {
}
public TrackCoach(FortuneService fortuneService) {
this.fortuneService = fortuneService;
}
@Override
public String getDailyWorkout() {
return "Run a hard 5k";
}
@Override
public String getDailyFortune() {
return "Just Do It: " + fortuneService.getFortune();
}
}
OutPut:
Run a hard 5k
Just Do It: Today is your lucky day!
In the above program the fortune service is dependent on the tennis coach we have to create a constructor in the MySelf.java class to create the object but it takes the object of FortuneService so we have to inject the FortuneService in TennisCoach that's how we are injecting the dependency which is in theTennisCoach.java
How does CodersArts helps you ?
CodersArts provide :
Spring boot assignment Help
Help in development Projects
Mentorship from Experts Live 1:1 session
Course and Project completions
CourseWork help
Comments