Java의 Proxy 클래스를 이용하여 AOP(Aspect Oriented Programming)에 대해 설명한 적이 있다.(http://www.jaso.co.kr/4)
Spring 등과 같이 잘 만들어진 프레임워크를 이용할 수도 있지만 간단하게 몇개의 클래스만 만들어도 Spring 못지 않은 나만의 AOP 프레임워크를 구성할 수 있다.
최근 그때 만든것을 사용할 필요가 있어 사용하는 도중 뜻하지 않는 문제에 봉착했다. Proxy로 생성된 객체 내부에서 클래스 내부에 있는 메소드를 호출할 경우 InvocationHandler가 적용되지 않는다는 점이다.
다음 예를 보자.

public interface Test {

  public void print() ;

  public void innerMethod();

}


public class TestImpl implements Test {

  public void print() {

    System.out.println("This is test");

    innerMethod();    (1)

  } 
 
public void innerMethod() {

    System.out.println("called innerMethod");

  }

  public static void main(String[] args) throws Exception {

    Test test = (Test)ProxyFactory.createProxyClass("test");

    test.print();

    test.innerMethod();  (2)

  }

}



이 경우 (2)에서 호출한 innerMethod의 경우 InvocationHandler를 거쳐 호출되지만, (1)에서 호출된 경우에는 InvocationHandler를 거치지 않는다.
Proxy.isProxyClass()를 이용하면 쉽게 알 수 있다. (2)에 있는 test 객체에 대해 다음과 같이 하면 True가 반환된다.

Proxy.isProxyClass(test.getClass())

innerMethod() 내부에서 다음과 같은 코드를 작성하면 false가 반환된다.

Proxy.isProxyClass(this.getClass())

내부 메소드 호출에서도 InvocationHandler가 동작하게 하기 위해서는 Proxy를 이용해서 생성된 객체를 다시 해당 클래스에 설정하고 내부 메소드 호출시에는 그 클래스를 이용하도록 하는 방법을 사용하면 된다.

public class TestImpl implements Test {

  Test proxyClass;

  public void print() {

    System.out.println("This is test");

    proxyClass.innerMethod();

  } 
 
public void innerMethod() {

    System.out.println("called innerMethod");

  }

  public void setProxyClass(Test test) {

    proxyClass = test;

  }

  public static void main(String[] args) throws Exception {

    Test test = (Test)ProxyFactory.createProxyClass("test");

    test.setProxyClass(test);

    test.print();

    test.innerMethod();

  }

}

크리에이티브 커먼즈 라이센스
Creative Commons License

Posted by 김형준


Trackback URL : http://www.jaso.co.kr/trackback/182

Leave a comment
« Previous : 1 : ... 240 : 241 : 242 : 243 : 244 : 245 : 246 : 247 : 248 : ... 388 : Next »