简单的实现示例如下:
public class A {//含有显示字母“A”的行为do
public void do(){
System.out.println( “ A”);
}
}
import java.lang.reflect.Method;//类Before为切面
import org.springframework.aop.MethodBeforeAdvice;
public class Before implements MethodBeforeAdvice{
public void before(Method arg0,Object[] arg1,Object[] arg2)throws Throwable{
System.out.println(“ Bingo!”);
}
}
import org.springframework.beans.factory.BeanFactory;//运行AOP程序
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.CladdPathResource;
public class DoMain{
public static void main(String[] args){
ClassPathResource resource=new ClassPathResource(“beans.xml”);//配置文件载入内存
BeanFactory factory=new XmlBeanFactory(resource);//Bean Factory读取配置信息
A a=(A) factory.getBean(“a”);//对象实例化
a.do();//调用类A下的行为
}
}
运行上述main程序结果显示:
Bingo!
A
这说明在调用类A的行为do前程序已经自动把类Before以前置通知方式调用。以同样的方式AOP可以在对象上以After、Around、Throw方式附加切面,这很好的解决诸如身份验证、拦截通知等问题。拥有AOP技术的Spring可以减少代码耦合,提高系统的灵活性扩张性,还使得单元测试变得更为容易。