此方法只做演示,项目中不使用
项目中用annotation
此代码输出 "World"
package com.test532;
public class MessageWriter {
public void writeMessage(){
System.out.print("World");
}
}
如何使用AOP,在松耦合情况下输出 hello world !
以下代码实现:
package com.test532;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
//此类实现包围通知 MethodInterceptor
public class MethodDecorator implements MethodInterceptor{
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
System.out.print("Hello ");
Object retVal = invocation.proceed();
System.out.print(" !");
return retVal;
}
}
public class HelloWorldWriter {
public static void main(String[] args) {
MessageWriter writer = new MessageWriter();
//使用ProxyFactory是完全编程式的做法,一般我们不需要这么做,
//可以依靠ProxyFactoryBean类来声明式地创建代理
ProxyFactory factory = new ProxyFactory();//创建代理工厂
factory.addAdvice(new MethodDecorator());//织入通知
factory.setTarget(writer);//设定织入的目标对象
MessageWriter proxy = (MessageWriter)factory.getProxy(); //获得代理
proxy.writeMessage();
}
}
打印出:
Hello World !