2014년 2월 11일 화요일

ProxyFactory를 이용한 프로그램을 통한 AOP구현예제(Spring Framework3.X AOP구현하기,Advice, Pointcut), 스프링프레임워크 AOP강좌

ProxyFactory를 이용한 프로그램을 통한 AOP구현예제(Spring Framework3.X AOP구현하기,Advice, Pointcut), 스프링프레임워크 AOP강좌

- 다음과 같은 인터페이스와 타겟 클레스가 있다. 

interface OnjWorld { 
public void onjHello(); 
        public void onjHello2(); 


public class OnjWorldImpl implements OnjWorld { 
public void onjHello() { 
System.out.println("OnJ에오신것을 환영합니다."); 

public void onjHello2() { 
System.out.println("OnJ2에오신것을 환영합니다."); 
}


위 OnjWorldImpl이 타겟 클래스이다. onjHello2 로 시작하는 메소드에 스프링 충고를 내릴려고 한다. 
충고(Advice)는 적당히 콘솔화면에 출력하는 정도로 만들고... 
before advice, around advice, throws advice, ,after returning advice를 구현하시오. 

- 프로그래밍적인 방법으로 구현해 보았다.


정적인 클래스 이름과 메소드 이름으로 포인트컷을 만들기 위해 StaticMethodMatcherPointcut을 상속해서 포인트컷을 만들었고...  기존 예제와 다든 점은 하나의 어드바이스에 충고가 여러개인 경우를 처리하는 방법입니다. 

OnjClient.java 예제를 참고하세요. 


0.0 인터페이스 OnjWorld.java

package onj.aop.programming;

interface OnjWorld {
public void onjHello();
public void onjHello2() throws Exception;
}


0.1 인터페이스 구현 클래스 OnjWorldImpl.java


package onj.aop.programming;

public class OnjWorldImpl implements OnjWorld {
public void onjHello() {
System.out.println("OnJ에오신것을 환영합니다.");
}

public void onjHello2() throws Exception {
System.out.println("OnJ2에오신것을 환영합니다.");
throw new Exception("OnJ Exception...");
}
}




1.AfterLoggingAdvice.java

package onj.aop.programming;

import java.lang.reflect.Method;

import org.springframework.aop.AfterReturningAdvice;

public class AfterLoggingAdvice implements AfterReturningAdvice {
public void afterReturning(Object arg0, Method arg1, Object[] arg2,
Object arg3) throws Throwable {
System.out.println(arg1.getName() + ":: 사후충고");
}
}



2. AroundLoggingAdvice.java

package onj.aop.programming;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

public class AroundLoggingAdvice implements MethodInterceptor {
public Object invoke(MethodInvocation arg0) throws Throwable {
System.out.println("메소드실행전...");
Object returnedObj = arg0.proceed();
System.out.println("메소드실행후...");
return returnedObj;
}// :}///~
}


3. BeforeLoggingAdvice.java

package onj.aop.programming;

import java.lang.reflect.Method;

import org.springframework.aop.MethodBeforeAdvice;

public class BeforeLoggingAdvice implements MethodBeforeAdvice{
public void before(Method arg0, Object[] arg1, Object arg2)throws Throwable{
System.out.println(arg0.getName() + "::: 사전충고");
}
}

4. ThrowsLoggingAdvice.java

package onj.aop.programming;


import org.springframework.aop.ThrowsAdvice;

public class ThrowsLoggingAdvice implements ThrowsAdvice {
public void afterThrowing(Throwable throwable) {
System.out.println(">>>>>>>> 에러발생 " + throwable);
}
}


5. 이번에는 포인트컷이다. SimpleStaticPointcut.java

   package onj.aop.programming;

import java.lang.reflect.Method;

import org.springframework.aop.ClassFilter;
import org.springframework.aop.support.StaticMethodMatcherPointcut;

public class SimpleStaticPointcut extends StaticMethodMatcherPointcut {// 아래는First.class의one()메소드일때충고가적용된다.
public boolean matches(Method method, Class<?> cls) {
return ("onjHello2".equals(method.getName()));
}

public ClassFilter getClassFilter() {
return new ClassFilter() {
public boolean matches(Class<?> cls) {
return (cls == OnjWorldImpl.class);
}
};
}
}


6. 실행을 위한 클라이언트 프로그램  OnjClient.java
 
충고가 여러개인 경우 충고마다 Advisor를 만들어서 ProxyFactory에 여러 Advisor 
넣었습니다.

package onj.aop.programming;

import org.aopalliance.aop.Advice;
import org.springframework.aop.Advisor;
import org.springframework.aop.Pointcut;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.DefaultPointcutAdvisor;

public class OnjClient {
public static void main(String[] args) {
OnjWorldImpl target = new OnjWorldImpl();
ProxyFactory pf = new ProxyFactory();
Pointcut pc = new SimpleStaticPointcut();
Advice before = new BeforeLoggingAdvice();
Advice after = new AfterLoggingAdvice();
Advice around = new AroundLoggingAdvice();
Advice throwsAdvice = new ThrowsLoggingAdvice();
Advisor advisor1= new DefaultPointcutAdvisor(pc,before);
Advisor advisor2= new DefaultPointcutAdvisor(pc,after);
Advisor advisor3= new DefaultPointcutAdvisor(pc,around);
Advisor advisor4= new DefaultPointcutAdvisor(pc,throwsAdvice);
pf.addAdvisors(advisor1,advisor2, advisor3, advisor4);
pf.setTarget(target);
try {
OnjWorld proxy = (OnjWorld) pf.getProxy();
proxy.onjHello();
proxy.onjHello2();
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
}


7. 결과

SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/C:/java/lib/slf4j-log4j12-1.7.5.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/C:/Documents%20and%20Settings/Administrator/.m2/repository/org/slf4j/slf4j-log4j12/1.6.6/slf4j-log4j12-1.6.6.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.slf4j.impl.Log4jLoggerFactory]
OnJ에오신것을 환영합니다.
onjHello2::: 사전충고
메소드실행전...
OnJ2에오신것을 환영합니다.
>>>>>>>> 에러발생 java.lang.Exception: OnJ Exception...
java.lang.Exception: OnJ Exception...
at onj.aop.programming.OnjWorldImpl.onjHello2(OnjWorldImpl.java:10)
at onj.aop.programming.OnjWorldImpl$$FastClassByCGLIB$$4c0178cb.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:698)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.aop.framework.adapter.ThrowsAdviceInterceptor.invoke(ThrowsAdviceInterceptor.java:124)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at onj.aop.programming.AroundLoggingAdvice.invoke(AroundLoggingAdvice.java:9)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor.invoke(AfterReturningAdviceInterceptor.java:51)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor.invoke(MethodBeforeAdviceInterceptor.java:51)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:631)
at onj.aop.programming.OnjWorldImpl$$EnhancerByCGLIB$$cb4b3dbf.onjHello2(<generated>)
at onj.aop.programming.OnjClient.main(OnjClient.java:35)


댓글 없음:

댓글 쓰기