How to create a loosely coupled Java application using
Spring Frameworks Dependency Injection ?
Let see First tightly coupled
public interface Animal {
public void makeNoise();
}
public class Dog implements Animal {
@Override
public void makeNoise() {
System.out.println("Dog is barking");
}
}
public class Lion implements Animal {
@Override
public void makeNoise() {
System.out.println("Lion is roaring");
}
}
public class AnimalService {
private Animal animal= new Dog();
public void makeSound(){
animal.makeNoise();
}
}
public class AnimalTest {
public static void main(String[] args) {
AnimalService animalService = new AnimalService();
animalService.makeSound();
}
}
As in service new operator is used. So in future if we want
to change from to Lion, we need to modify the java code.
Let’s see loose coupling
There is little changes in AnimalService & AnimalTest.
public class AnimalService {
private Animal animal;
public void setAnimal(Animal animal) {
this.animal = animal;
}
public void makeSound() {
animal.makeNoise();
}
}
public class AnimalTest {
public static void main(String[] args) {
ApplicationContext context= new ClassPathXmlApplicationContext("applicationContext.xml");
AnimalService animalService = (AnimalService) context.getBean("animalService");
animalService.makeSound();
}
}
applicationContext.xml
<bean id="dog" class="com.shambhu.model.Dog"
/>
<bean id="lion" class="com.shambhu.model.Lion"
/>
<bean id="animalService" class="com.shambhu.service.AnimalService">
<property name="animal" ref="dog"
/>
</bean>
As in AnimalService there is no new oper
AS in Animal service there is no new operator just
configured in xml, where we can change ref, with out touching java we can make
ref dog to lion.
0 comments: