Java의 Proxy를 이용한 AOP
Simple 예제
:namespace
prefix = o ns = "urn:schemas-microsoft-com:office:office" />
1.
HelloWorld Interface를
작성한다.
Proxy는 인터페이스를 통해서 객체를 생성하는 방식이므로 반드시 인터페이스가 필요하다.
[HelloWorld.java]
package proxy;
/**
* Proxy는
인터페이스를
통해서
객체를
생성하는
방식이므로
* 반드시
인터페이스가
필요하다.
* Spring에서
인터페이스가
없는
경우에는
CGLIB를
이용한다.
* @author tatata
*
*/
public interface HelloWorld {
public String sayHello(String msg);
}
2.
인터페이스 구현 클래스 작성
[HelloWorldImpl.java]
package proxy;
public class HelloWorldImpl implements HelloWorld{
public String sayHello(String msg) {
return "hi~ " + msg;
}
}
3.
전통적인 클라이언트 프로그램 작성
[OldClient.java]
package proxy;
/**
* 전통적인
형태의
클라이언트
모듈임.
* 인터페이스를
통한
느슨한
결합외
별다른
것
없음...
* @author tatata
*
*/
public class OldClient {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
HelloWorld hello =
new HelloWorldImpl();
System.out.println(hello.sayHello("JCLEE"));
}
}
4.
OldClient를
실행하여
결과를
확인
하자.
이클립스에서 클래스선택 후 à 마우스 우측버튼 à Run as à Java Applicatopn
5.
Proxy를 위한 Handler 클래스
작성
[HelloHandler.java]
package proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class HelloHandler implements InvocationHandler {
private Object targetObj = null;
public HelloHandler(Object target) {
this.targetObj = target;
}
public Object invoke(Object obj, Method method, Object[] args)
throws Throwable {
try {
System.out.println(" <<<<<<<<<< Start...");
System.out.println(method.getName());
System.out.println(args);
return method.invoke(targetObj, args);
}
catch(Exception e) {
throw e;
}
finally {
System.out.println(" <<<<<<<<<< END...");
}
}
}
오라클자바커뮤니티 추천 개발자 교육 - 개인80% 환급
댓글 없음:
댓글 쓰기