1 前篇基于xml的实现,这篇是基于代码实现,需要的jar包和前篇一样
2 Hello.java 代码
package aop.aop;
public interface Hello {
public void sayHello();
}
3 HelloImpl.java
package aop.aop;
public class HelloImpl implements Hello {
public void sayHello() {
System.out.println("hello");
}
}
4 MethodBeforeAdvice.java
package aop.aop;
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
public class BeforAdvice implements MethodBeforeAdvice {
public void before(Method arg0, Object[] arg1, Object arg2)
throws Throwable {
System.out.println("before");
}
}
package aop.aop;
import org.springframework.aop.framework.ProxyFactory;
public class Test {
public static void main(String[] args) {
//初始化类
Hello hello = new HelloImpl();
BeforAdvice beforAdvice= new BeforAdvice();
//代理类组装对象
ProxyFactory ps = new ProxyFactory();
ps.setTarget(hello);
ps.addAdvice(beforAdvice);
//获取对象
Hello h = (Hello)ps.getProxy();
h.sayHello();
}
}
6 输出结果
before
hello