AOP(Aspect Orient Programming),面向切面编程,做为面向对象的一种补充,用于处理系统中分布于各个模块的横切关注点,好比事务管理、日志、缓存等等。spring
AOP实现的关键在于AOP框架自动建立的AOP代理,AOP代理主要分为静态代理和动态代理:编程
静态代理,在编译期实现,动态代理是运行期实现。缓存
本文主要介绍Spring AOP的两种代理实现方式:JDK动态搭理和CGLIB动态代理框架
JDK动态搭理,经过反射来接收被代理的类,而且要求被代理的类必须实现一个接口。JDK动态代理的核心是InvocationHandler接口和Proxy类测试
若是目标类没有实现接口,那么Spring AOP会选择使用CGLIB来动态代理目标类。CGLIB,是一个代码生成的类库,能够在运行时动态的生成某个类的子类。注意,CGLIB经过继承的方式实现动态代理,所以若是某个类被标记为final,那么它是没法使用CGLIB作动态代理的,诸如private的方法也是不能够做为切面的。spa
<aop:aspectj-autoproxy />
@Aspect @Component public class MonitorAdvice { @Pointcut("execution(* com.demo.modul.user.service.Speakable.*(..))") public void pointcut() {} @Around("pointcut()") public void around(ProceedingJoinPoint jp) throws Throwable { MonitorSession.begin(jp.getSignature().getName()); jp.proceed(); MonitorSession.end(); } }
public static void main(String[] args) { // TODO Auto-generated method stub ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring-annotation-aop.xml"); /*AnnotationBusiness business = (AnnotationBusiness) context.getBean("annotationBusiness"); business.delete("JACK"); */ Speakable business = (Speakable) context.getBean("personSpring"); business.sayBye(); }