推荐 个网购 优惠券 领取网站 U券网 uquanfree.com 点击链接进入

Spring的AOP可以通过对@AspectJ注解的支持和在XML中配置来实现,本文通过实例简述如何在Spring中使用AspectJ.

一:使用AspectJ注解:

1,启用对AspectJ的支持:
        通过在Spring的配置中引入下列元素来启用Spring对AspectJ的支持:

<aop:aspectj-autoproxy/>

maven工程要先添加相应的 Aspectj的依赖

<!--AOP-->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjrt</artifactId>
    <version>1.8.9</version>
</dependency>
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.8.9</version>
</dependency>

2,声明一个带有@Aspect注解的类,在这个类中声明那些方法需要被'关注'(利用@Pointcut),在那些时机点进行关注(利用@Before,@AfterReturning等等...),执行'切入'的方法

@Aspect
public class AbcAspect {

3,在Spring的配置文件中定义这个'切面'类:任意带有一个@Aspect切面(拥有@Aspect注解)的bean都将被Spring自动识别并用于配置在Spring AOP.

@Pointcut("execution (* com.sans.pc.reco(*))"
)
public void aspect() {}

4,使用被Spring管理的bean,在执行被'关注'的方法时,'切入'的方法就会被执行.
一个完整的例子:
需要被'切入'的类:

public class Monkey {public void stealPeaches(String name) {System.out.println(" Monkey " + name + " is stealling peaches...");}public void stealCorns(String name) {System.out.println(" Monkey " + name + " is stealling corns...");}
}

'切面'类:

@Aspect
public class Guardian {@Pointcut("execution(* com.test.spring.aspectj.Monkey.stealPeaches(..))")public void guardOrchard() {}@Before(value = "guardOrchard()")public void guardOrchardBefore() {System.out.println("Guardian spotted a monkey is approaching the orchard...");}@AfterReturning("guardOrchard() && args(name,..)")public void guardOrchardAfter(String name) {System.out.println("Guardian caught a monkey stealling peaches whoes name is " + name + "...");}@Around("guardOrchard() && args(name,..)")
  public void guardOrchardAround(ProceedingJoinPoint joinpoint,String name) {
    System.out.println("Guardian guardOrchardAround started ... " + name);
    try {
      joinpoint.proceed();
    } catch (Throwable e) {
      System.out.println("Guardian guardOrchardAround exception happened ... " + name);
    }System.out.println("Guardian guardOrchardAround completed ... " + name);
  }@Pointcut("execution(* com.test.spring.aspectj.Monkey.stealCorns(..))")public void guardFarm() {}@Before(value = "guardFarm()")public void guardFarmBefore() {System.out.println("Guardian spotted a monkey is approaching the farm...");}@AfterReturning("guardFarm() && args(name,..)")public void guardFarmAfter(String name) {System.out.println("Guardian caught a monkey stealling corns whoes name is " + name + "...");}
}

配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"xsi:schemaLocation="    http://www.springframework.org/schema/beans    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd    http://www.springframework.org/schema/aop    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"><!--<aop:aspectj-autoproxy /> equals to <beanclass="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator"/>--><aop:aspectj-autoproxy /><bean id="guardian" class="com.test.spring.aspectj.Guardian" /><bean id="monkey" class="com.test.spring.aspectj.Monkey" /></beans>

使用bean:

ApplicationContext context = new ClassPathXmlApplicationContext("conf/aspectJAppcontext.xml");Monkey monkey = (Monkey) context.getBean("monkey");try {monkey.stealPeaches("mighty monkey");monkey.stealCorns("mighty monkey");} catch (Exception e) {}

运行结果:

Guardian spotted a monkey is approaching the orchard...
Guardian guardOrchardAround started ... mighty monkey
Monkey mighty monkey is stealling peaches...
Guardian caught a monkey stealling peaches whoes name is mighty monkey...
Guardian guardOrchardAround completed ... mighty monkey
Guardian spotted a monkey is approaching the farm...Monkey mighty monkey is stealling corns...
Guardian caught a monkey stealling corns whoes name is mighty monkey...

二:通过XML配置AspectJ实现AOP:在java类中定义要被'方面'调用的切入方法,在XML中配置.

例子:被'切入'的类,普通java类:

public class Monkey {public void stealPeaches(String name) {System.out.println(" Monkey " + name + " is stealling peaches...");}public void stealCorns(String name,int numberToSteal) {System.out.println(" Monkey " + name + " is stealling corns...");}
}

定义要被'方面'调用的切入方法的类:

public class XMLGuardian {public void guardOrchardBefore() {System.out.println("XMLGuardian spotted a monkey is approaching the orchard...");}public void guardOrchardAfter() {System.out.println("XMLGuardian caught a monkey stealling peaches whoes name is ...");}public void guardFarmBefore() {System.out.println("XMLGuardian spotted a monkey is approaching the farm...");}public void guardFarmAfter(String name,int num,Object retVal) {System.out.println("XMLGuardian caught a monkey stealling " + num + " corns whoes name is ..." + name );}
}

XML配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"xsi:schemaLocation="    http://www.springframework.org/schema/beans    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd    http://www.springframework.org/schema/aop    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"><bean id="guardian" class="com.test.spring.aspectj.XMLGuardian" /><bean id="monkey" class="com.test.spring.aspectj.Monkey" /><aop:config><aop:aspect id="myAspect" ref="guardian"><aop:pointcut id="guardOrchard"expression="execution(* com.test.spring.aspectj.Monkey.stealPeaches(..))" /><aop:before pointcut-ref="guardOrchard" method="guardOrchardBefore" /><aop:after-returning pointcut-ref="guardOrchard" method="guardOrchardAfter"/><aop:pointcut id="guardFarm"expression="execution(* com.test.spring.aspectj.Monkey.stealCorns(..))" /><aop:before pointcut-ref="guardFarm" method="guardFarmBefore" /><aop:after-returning pointcut="execution(* com.test.spring.aspectj.Monkey.stealCorns(..)) and args(name,num,..)" returning="retVal"method="guardFarmAfter" /><!--  arg-names="name1" --></aop:aspect>       </aop:config>
</beans>

客户端测试代码:

ApplicationContext context = new ClassPathXmlApplicationContext("conf/xmlaspectJAppcontext.xml");Monkey monkey = (Monkey) context.getBean("monkey");try {monkey.stealPeaches("mighty monkey");monkey.stealCorns("mighty monkey",3);} catch (Exception e) {}

运行结果:

XMLGuardian spotted a monkey is approaching the orchard...Monkey mighty monkey is stealling peaches...
XMLGuardian caught a monkey stealling peaches whoes name is ...
XMLGuardian spotted a monkey is approaching the farm...Monkey mighty monkey is stealling corns...
XMLGuardian caught a monkey stealling 3 corns whoes name is ...mighty monkey

Spring AOP 只支持对bean的方法级的'切入',而且AOP的内部机制和AspectJ有所区别,Spring主要是通过动态代理来实现AOP,使用JDK的动态代理(如果被代理的bean是interface的话)或者CGLIB(如果如果被代理的bean不是interface的话).

spring中使用Aspectj进行切面编程相关推荐

  1. spring aop实例讲解_小实例理解Spring中的AOP----面向切面编程

    关于面向切面编程(Spring AOP),是在java面试中经常提及的,只有在充分理解了,日常工作中才能得心应手. 如何理解AOP呢?首先我们要思考为什么要使用切面编程,如下图: 对于一个系统来说保存 ...

  2. 在Android中使用AspectJ进行切面编程的简易步骤

    最近有做用户行为统计的需求,为了尽可能使统计代码不侵入业务代码,就研究了下hook和Aop. 之前写的hook方面的文章里,有评论给出了些建议,于是研究了下AspectJ,虽然还是不能完美解决项目中的 ...

  3. 2014-03-11 Spring的学习(3)------面向切面编程(AOP)

    2019独角兽企业重金招聘Python工程师标准>>> 1. AOP概念 首先让我们从一些重要的AOP概念和术语开始.这些术语不是Spring特有的.不过AOP术语并不是特别的直观, ...

  4. 【SSM框架系列】Spring 的 AOP(面向切面编程)

    什么是 AOP AOP 为 Aspect Oriented Programming 的缩写,意思为面向切面编程,是通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术. AOP 是 OOP ...

  5. Spring学习之AOP(面向切面编程)

    动态代理 代理模式是常用的java设计模式,他的特征是代理类与委托类有同样的接口,代理类主要负责为委托类预处理消息.过滤消息.把消息转发给委托类,以及事后处理消息等.代理类与委托类之间通常会存在关联关 ...

  6. Spring核心AOP(面向切面编程)总结

    (尊重劳动成果,转载请注明出处:http://blog.csdn.net/qq_25827845/article/details/75208354冷血之心的博客) 目录 1.AOP概念: 2.AOP特 ...

  7. spring之AOP(面向切面编程)和五大通知(前置通知、后置通知、异常通知、环绕通知、过滤通知)

    一.aop的介绍 1.AOP中关键性概念 : 连接点(Joinpoint):程序执行过程中明确的点,如方法的调用,或者异常的抛出. 目标(Target):被通知(被代理)的对象 注1:完成具体的业务逻 ...

  8. Spring核心AOP(面向切面编程)

    AOP(面向切面编程) 原理 相关术语 系统日志增强 异常抛出增强 最终增强 环绕增强 使用注解实现AOP AspectJ 转载于:https://www.cnblogs.com/xhddbky/p/ ...

  9. java切面不需要接口了吗_使用java语言,如何对一个类中的静态方法做切面编程?...

    展开全部 package com.classloader.test; import java.lang.reflect.InvocationTargetException; import java.l ...

最新文章

  1. [Xcode 实际操作]六、媒体与动画-(1)使用图形上下文按一定比例缩放图片
  2. P6620 [省选联考 2020 A 卷] 组合数问题(斯特林数、下降幂)
  3. java 用户名不为空_[Java教程]【关于JavaScript】常见表单用户名、密码不能为空
  4. swagger2 配置访问路径_有了Swagger2 再也不用担心API文档的维护了
  5. 【bug解决】No OpKernel was registered to support Op 'CudnnRNN' with these attrs.
  6. QT ——添加多国语言
  7. 闲置商标转让怎样管理最好?
  8. struts2与jasperreport整合其余问题
  9. 综合能源服务认证的定义,综合能源服务认证意义
  10. 数据质量监控工具-Apache Griffin
  11. python自动化模拟浏览器
  12. 全自动过滤器:全自动叠片过滤器工作原理及应用范围
  13. 少说话多写代码之Python学习048——类的成员(supper函数)
  14. mysql日志分析工具之mysqlsla
  15. nanopi neo core学习(二)网络设置
  16. python趣味程序_知道了这个,你也能写出 Python 趣味小程序
  17. c语言寒假作业班干选举系统,寒假作业1
  18. JS-Web-API
  19. 冒险岛m服务器维修,冒险岛m新手攻略
  20. 大学本科的计算机专业学生,应该达到什么能力水平,才算上合格?

热门文章

  1. Python基础知识入门PartII
  2. 项目07城市餐饮店铺选址分析
  3. 前端学习笔记 - 用CSS实现一个背景色为红色,半径为200px的圆,并设置不停的上下移动动画
  4. 英文文本关键词抽取——使用NLTK进行关键词抽取
  5. 地铁牵引供电系统MATLAB/Simulink仿真建模
  6. ffmpeg使用记录--解决了压制的视频在安卓不播放的问题
  7. 图神经网络-图与图学习笔记-1
  8. JAVA 酒店预订系统
  9. 狗狗先天遗传性格如何改变
  10. 电商领域用户的留存分析