Spring Framework

Spring Projects

Spring Project 1

Example of JDK Dynamic Proxy
Previous Home Next

Introduction: JDK dynamic proxy provided by sun micro system through the reflection API to create runtime proxy object then provide the services before invocation of method and after invocation of method.

Technology use to run this source code

  1. Spring 2.5 jar files
  2. Eclipse IDE
  3. Tomcat Server

Source Code:

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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
</beans>

 

A.java

package org.r4r;
public class A implements Printable {
@Override
public void print() {
System.out.println("print() mathod of A is invoked..");
}
}

Printable.java

package org.r4r;
public interface Printable {
public void print();
}

PrintHandler.java

package org.r4r;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class PrintHandler implements InvocationHandler {
Object target;
public PrintHandler(Object target) {
super();
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println
("Handler invoked invoking\t"
+method.getName()+"() one target object.....");
//advices can be inserted here before actual method call.
Object r=method.invoke(target, args);
//advices can be inserted here after actual method call.
System.out.println
("Method call completed, returning value\t"
+"return by actual method");
return r;
}
}

ProxyTest.java

package org.r4r;
import java.lang.reflect.Proxy;
public class ProxyTest {
public static void main(String[] args) {
try{
System.out.println("Creating target object.....");
A target=new A();
System.out.println("Creating handler....");
PrintHandler handler=new PrintHandler(target);
System.out.println("Creating proxy,,,");
Printable proxy=(Printable)Proxy.newProxyInstance
(target.getClass().getClassLoader(),
 target.getClass().getInterfaces(), handler);
System.out.println("invoking print() on proxy.....");
proxy.print();
}catch(Exception e){
System.out.println(e);
}
}
}

output:

 Creating target object.....
Creating handler....
Creating proxy,,,
invoking print() on proxy.....
Handler invoked invokingprint() one target object.....
print() mathod of A is invoked..
Method call completed, returning valuereturn by actual method
Previous Home Next

Tolal:0 Click:

Show All Comments

Did not find what you were looking for leave your name and message. We will revert within 24 hours
Name:
eMail:
Comment / Feedback: