Spring AOP实战

AOP(Aspect Orient Programming),面向切面编程,做为面向对象的一种补充,用于处理系统中分布于各个模块的横切关注点,好比事务管理、日志、缓存等等。spring

AOP实现的关键在于AOP框架自动建立的AOP代理,AOP代理主要分为静态代理动态代理编程

  • 静态代理的表明为,AspectJ
  • 动态代理,则以Spring AOP为表明

静态代理,在编译期实现,动态代理是运行期实现缓存

  • 静态代理,是编译阶段生成AOP代理类,也就是说生成的字节码就已织入了加强后的AOP对象;
  • 动态代理,不会修改字节码,而是在内存中临时生成一个AOP对象,该AOP对象包含了目标对象的所有方法,而且在特定的切点作了加强处理,并回调原对象的方法

本文主要介绍Spring AOP的两种代理实现方式:JDK动态搭理和CGLIB动态代理框架

  • JDK动态搭理,经过反射来接收被代理的类,而且要求被代理的类必须实现一个接口。JDK动态代理的核心是InvocationHandler接口和Proxy类测试

  • 若是目标类没有实现接口,那么Spring AOP会选择使用CGLIB来动态代理目标类。CGLIB,是一个代码生成的类库,能够在运行时动态的生成某个类的子类。注意,CGLIB经过继承的方式实现动态代理,所以若是某个类被标记为final,那么它是没法使用CGLIB作动态代理的,诸如private的方法也是不能够做为切面的。spa

直接使用Spring AOP

  • xml配置文件中需开启**<aop:aspectj-autoproxy />**
  • 定义基于注解的Advice:@Aspect,@Component,@Pointcut,@Before,@Around,@After。。。
  1. 配置文件开启AOP注解
<aop:aspectj-autoproxy />
  1. 基于注解的Advice
@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();
	}
}
  1. 测试:
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();
	}

基于JDK动态代理

相关文章
相关标签/搜索