读书人

AOP 学习, ProxyFactory 学习1

发布时间: 2012-08-24 10:00:21 作者: rapoo

AOP 学习, ProxyFactory 学习一
Advice: 拦截的切面

ProxyFactory: 简单使用

使用ProxyFactory, 需要指定其两个属性

setTarget: 拦截目标
addAdvice: 切面, 也就是拦截目标时你要执行的动作

public class MessageWriter {public void showMessage(){System.out.println("this is a test");}}import org.aopalliance.intercept.MethodInterceptor;import org.aopalliance.intercept.MethodInvocation;public class MessageDecorator implements MethodInterceptor{public Object invoke(MethodInvocation invocation) throws Throwable{System.out.print("hello\n");Object retVal=invocation.proceed();System.out.print("end");return retVal;}}import org.springframework.aop.framework.ProxyFactory;public class test {public static void main(String[] args) {MessageWriter target =new MessageWriter();ProxyFactory pf=new ProxyFactory(target);/* or  ProxyFactory pf=new ProxyFactory();  ps.setTarget(target); */pf.addAdvice(new MessageDecorator()); MessageWriter proxy=(MessageWriter)pf.getProxy();proxy.showMessage();}}

result:
hellothis is a testend

读书人网 >软件架构设计

热点推荐