Wednesday, May 23, 2012

Spring Framework-Decoupling with interface


To solve out the coupling problems like-difficult to test,difficult to reuse and understand decoupling is used with interface.Lets take a example tour to understand.
directory structure of project-
                                                         
Interface HelloApp.java
package com.test;

public interface HelloApp {
public void draw();
}

class Triangle.java
package com.test;

public class Triangle implements HelloApp {
public void draw()
{
System.out.println("Hello Triangle");
}

}

class Rectangle.java
package com.test;

public class Rectangle implements HelloApp {
public void draw() {
System.out.println("Hello Ractangle");
}
}


class DrawApp.java(Main class)
package com.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class DrawApp {

public static void main(String a[])
{
ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
HelloApp tri=(HelloApp) context.getBean("triangle");
tri.draw();
tri=(HelloApp) context.getBean("ract");
tri.draw();
}
}


Spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="triangle" class="com.test.Triangle"/>
<bean id="ract" class="com.test.Rectangle"/>
</beans>

Output is-
Hello Triangle
Hello Rectangle






For Further Reading,
General, Java, spring

0 comments:

Post a Comment


 

Site Status

Man Behind Technical Today

Hello, I am Navin Bansal. I am a student of MCA in Rajsthan Institute of Engineering and Technology and owner of this blog. I share my view and ideas among people.