Powered by Blogger.

Thursday 12 June 2014

Loose coupling in Spring

By Unknown  |  04:36 No comments

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.



Author: Unknown

Hello, I am Author, decode to know more: In commodo magna nisl, ac porta turpis blandit quis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. In commodo magna nisl, ac porta turpis blandit quis. Lorem ipsum dolor sit amet.

0 comments:

Recent Articles

© 2014 Learning Java. WP themonic converted by Bloggertheme9. Published By Gooyaabi Templates
TOP