spring-aop---AspectJ注解式切面编程。
2017-10-01 15:08
387 查看
SpringAOP中是直接用AspectJ的的注解来使用,这些注解是AspectJ5之后引入的特性。如不做其他设置,注解方式依旧是用的JdkDynamicAopProxy类来生成实现类,面向接口生成。因为注解式属于AspectJ体系的,因此我们需要在配置文件中手动注册一个
AnnotationAwareAspectJAutoProxyCreator
bean来将带有@Aspect注解的bean在编译器动态生成代理类,将切面织入到代理类中。
publicinterfaceUser{publicvoidsay();}
@ComponentpublicclassUserImplimplementsUser{publicvoidsay(){System.out.println("helloaop!");}}
@Aspect//注解属于AspectJ@Component//在spring中注册为bean,纳入管理publicclassAnnoAspect{@Pointcut("execution(*demo.entity.User.*(..))")publicvoidpointcut(){};@Before("pointcut()")publicvoidbefore(){System.out.println("beforerun...");}@After("pointcut()")publicvoidafter(){System.out.println("afterrun...");}@Around("pointcut()")publicvoidaround(ProceedingJoinPointproceedingJoinPoint)throwsThrowable{proceedingJoinPoint.proceed();System.out.println("aroundrun...");}@AfterThrowing("pointcut()")publicvoidthrowEx(){System.out.println("throwex...");}}
ApplicationContextapplicationContext=newClassPathXmlApplicationContext("/spring.xml");//getBean这次直接返回动态代理类Useruser=(User)applicationContext.getBean("userImpl");user.say();输出
beforerun...helloaop!aroundrun...afterrun...
注意我们依旧是用的接口来接受代理类。
然后看配置文件中这一个类名是太长了。。因此spring又对此进行了优化,只需要开启某个配置即可替换这个注册这个bean。
<aop:aspectj-autoproxy>表示开启AspectJ的面向接口的动态代理生成,而不再使用spring的动态代理方式,区别就是一个是编译时生成代理类,一个是运行时生成代理类。
输出
beforerun...helloaop!aroundrun...afterrun...
现在依旧是面向接口的,我们要使用CGLib子类代理呢。像昨天那样一样作就行了。
成功输出
beforerun...helloaop!aroundrun...afterrun...
然后仔细看我们的配置文件,以下配置和我们昨天的配置是一样的,因此我们就可以得出如下结论。
<aop:aspectj-autoproxyproxy-target-class="true"/>
1.spring声明式和变成式在运行时,动态生成一个面向接口的代理子类。
2.spring的注解式是使用了AspectJ的注解,必须使用<aop:aspectj-autoproxy/>标签开启对AspectJ的支持。
在编译时,spring动态生成一个面向接口的代理子类。
3.不管是spring还是AspectJ如果要使用CGLib代理开启<aop:aspectj-autoproxyproxy-target-class="true"/>标签。
在编译时,spring动态生成一个实现类的代理子类。
相关文章推荐
- Spring AOP 面向切面编程 常见通知实现(前置,后置,环绕,异常)
- spring系列(三):切面编程(aop)1
- 【我看Spring】从一个简单的AOP示例看切面编程
- Spring的AOP面向切面编程
- 重新学习之spring第二个程序,配置AOP面向切面编程
- 从源码入手,一文带你读懂Spring AOP面向切面编程
- spring切面编程AOP 范例一
- spring_由注解实现AOP面向切面编程_实现动态代理
- Spring面向切面编程AOP(around)
- Spring AOP切面编程
- 使用Spring进行面向切面(AOP)编程
- spring的AOP--面向切面编程
- Spring 面向切面编程AOP
- Spring AOP:使用NameMatchMethodPointcutAdvisor实现切面编程
- 什么是SpringAop? 面向切面编程-----思想
- Spring面向切面编程——Spring实现AOP方式——通过Spring API实现
- Spring 面向切面编程AOP
- Spring基础配置(AOP切面编程)
- aspectj 使用spring AOP切面编程的时候报错:ReflectionWorld$ReflectionWorldException NoClassDefFoundError 的处理
- springAOP面向切面编程之日志记录功能