2019独角兽企业重金招聘Python工程师标准>>>

基于注解的方式实现通知

1.需要的jar包:

com.springsource.net.sf.cglib-2.2.0.jar
com.springsource.org.aopalliance-1.0.0.jar
com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
commons-logging-1.1.1.jar
spring-aop-4.0.0.RELEASE.jar
spring-aspects-4.0.0.RELEASE.jar
spring-beans-4.0.0.RELEASE.jar
spring-context-4.0.0.RELEASE.jar
spring-core-4.0.0.RELEASE.jar
spring-expression-4.0.0.RELEASE.jar

2.实现类:

注意:由于是使用注解的方式所以需要在实现类中添加注解

如下:

package com.atguigu.spring.aop;public interface ArithmeticCalculator {int add(int i, int j);int sub(int i, int j);int mul(int i, int j);int div(int i, int j);}package com.atguigu.spring.aop;import org.springframework.stereotype.Component;@Component("arithmeticCalculator")
public class ArithmeticCalculatorImpl implements ArithmeticCalculator {@Overridepublic int add(int i, int j) {int result = i + j;return result;}@Overridepublic int sub(int i, int j) {int result = i - j;return result;}@Overridepublic int mul(int i, int j) {int result = i * j;return result;}@Overridepublic int div(int i, int j) {int result = i / j;return result;}}

3.配置文件:

<?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"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"><!-- 自动扫描的包 --><context:component-scan base-package="com.atguigu.spring.aop"></context:component-scan><!-- 使 AspectJ 的注解起作用 --><aop:aspectj-autoproxy></aop:aspectj-autoproxy></beans>

4.通知切面(1):

import java.util.Arrays;import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;/*** AOP 的 helloWorld* 1. 加入 jar 包* com.springsource.net.sf.cglib-2.2.0.jar* com.springsource.org.aopalliance-1.0.0.jar* com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar* spring-aspects-4.0.0.RELEASE.jar* * 2. 在 Spring 的配置文件中加入 aop 的命名空间。 * * 3. 基于注解的方式来使用 AOP* 3.1 在配置文件中配置自动扫描的包: <context:component-scan base-package="com.atguigu.spring.aop"></context:component-scan>* 3.2 加入使 AspjectJ 注解起作用的配置: <aop:aspectj-autoproxy></aop:aspectj-autoproxy>* 为匹配的类自动生成动态代理对象. * * 4. 编写切面类: * 4.1 一个一般的 Java 类* 4.2 在其中添加要额外实现的功能. ** 5. 配置切面* 5.1 切面必须是 IOC 中的 bean: 实际添加了 @Component 注解* 5.2 声明是一个切面: 添加 @Aspect* 5.3 声明通知: 即额外加入功能对应的方法. * 5.3.1 前置通知: @Before("execution(public int com.atguigu.spring.aop.ArithmeticCalculator.*(int, int))")* @Before 表示在目标方法执行之前执行 @Before 标记的方法的方法体. * @Before 里面的是切入点表达式: * * 6. 在通知中访问连接细节: 可以在通知方法中添加 JoinPoint 类型的参数, 从中可以访问到方法的签名和方法的参数. * * 7. @After 表示后置通知: 在方法执行之后执行的代码. *///通过添加 @Aspect 注解声明一个 bean 是一个切面!
@Aspect
@Component
public class LoggingAspect {@Before("execution(public int com.atguigu.spring.aop.ArithmeticCalculator.*(int, int))")public void beforeMethod(JoinPoint joinPoint){String methodName = joinPoint.getSignature().getName();Object [] args = joinPoint.getArgs();System.out.println("The method " + methodName + " begins with " + Arrays.asList(args));}@After("execution(* com.atguigu.spring.aop.*.*(..))")public void afterMethod(JoinPoint joinPoint){String methodName = joinPoint.getSignature().getName();System.out.println("The method " + methodName + " ends");}}

5.测试实现1:

package com.atguigu.spring.aop;import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class Main {public static void main(String[] args) {ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-aop.xml");ArithmeticCalculator arithmeticCalculator = (ArithmeticCalculator) ctx.getBean("arithmeticCalculator");System.out.println(arithmeticCalculator.getClass().getName());int result = arithmeticCalculator.add(11, 12);System.out.println("result:" + result);result = arithmeticCalculator.div(21, 3);System.out.println("result:" + result);}}

6.通知切面2及切面优先级:

package com.atguigu.spring.aop;import java.util.Arrays;import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;/*** 可以使用 @Order 注解指定切面的优先级, 值越小优先级越高*/
@Order(2)
@Aspect
@Component
public class LoggingAspect {/*** 定义一个方法, 用于声明切入点表达式. 一般地, 该方法中再不需要添入其他的代码. * 使用 @Pointcut 来声明切入点表达式. * 后面的其他通知直接使用方法名来引用当前的切入点表达式. */@Pointcut("execution(public int com.atguigu.spring.aop.ArithmeticCalculator.*(..))")public void declareJointPointExpression(){}/*** 在 com.atguigu.spring.aop.ArithmeticCalculator 接口的每一个实现类的每一个方法开始之前执行一段代码*/@Before("declareJointPointExpression()")public void beforeMethod(JoinPoint joinPoint){String methodName = joinPoint.getSignature().getName();Object [] args = joinPoint.getArgs();System.out.println("The method " + methodName + " begins with " + Arrays.asList(args));}/*** 在方法执行之后执行的代码. 无论该方法是否出现异常*/@After("declareJointPointExpression()")public void afterMethod(JoinPoint joinPoint){String methodName = joinPoint.getSignature().getName();System.out.println("The method " + methodName + " ends");}/*** 在方法法正常结束受执行的代码* 返回通知是可以访问到方法的返回值的!*/@AfterReturning(value="declareJointPointExpression()",returning="result")public void afterReturning(JoinPoint joinPoint, Object result){String methodName = joinPoint.getSignature().getName();System.out.println("The method " + methodName + " ends with " + result);}/*** 在目标方法出现异常时会执行的代码.* 可以访问到异常对象; 且可以指定在出现特定异常时在执行通知代码*/@AfterThrowing(value="declareJointPointExpression()",throwing="e")public void afterThrowing(JoinPoint joinPoint, Exception e){String methodName = joinPoint.getSignature().getName();System.out.println("The method " + methodName + " occurs excetion:" + e);}/*** 环绕通知需要携带 ProceedingJoinPoint 类型的参数. * 环绕通知类似于动态代理的全过程: ProceedingJoinPoint 类型的参数可以决定是否执行目标方法.* 且环绕通知必须有返回值, 返回值即为目标方法的返回值*//*@Around("execution(public int com.atguigu.spring.aop.ArithmeticCalculator.*(..))")public Object aroundMethod(ProceedingJoinPoint pjd){Object result = null;String methodName = pjd.getSignature().getName();try {//前置通知System.out.println("The method " + methodName + " begins with " + Arrays.asList(pjd.getArgs()));//执行目标方法result = pjd.proceed();//返回通知System.out.println("The method " + methodName + " ends with " + result);} catch (Throwable e) {//异常通知System.out.println("The method " + methodName + " occurs exception:" + e);throw new RuntimeException(e);}//后置通知System.out.println("The method " + methodName + " ends");return result;}*/
}
package com.atguigu.spring.aop;import java.util.Arrays;import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;@Order(1)
@Aspect
@Component
public class VlidationAspect {@Before("com.atguigu.spring.aop.LoggingAspect.declareJointPointExpression()")public void validateArgs(JoinPoint joinPoint){System.out.println("-->validate:" + Arrays.asList(joinPoint.getArgs()));}}

7测试2:

package com.atguigu.spring.aop;import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class Main {public static void main(String[] args) {ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");ArithmeticCalculator arithmeticCalculator = (ArithmeticCalculator) ctx.getBean("arithmeticCalculator");System.out.println(arithmeticCalculator.getClass().getName());int result = arithmeticCalculator.add(1, 2);System.out.println("result:" + result);result = arithmeticCalculator.div(1000, 10);System.out.println("result:" + result);}}

基于xml文件配置的方式

package com.atguigu.spring.aop.xml;public interface ArithmeticCalculator {int add(int i, int j);int sub(int i, int j);int mul(int i, int j);int div(int i, int j);}package com.atguigu.spring.aop.xml;public class ArithmeticCalculatorImpl implements ArithmeticCalculator {@Overridepublic int add(int i, int j) {int result = i + j;return result;}@Overridepublic int sub(int i, int j) {int result = i - j;return result;}@Overridepublic int mul(int i, int j) {int result = i * j;return result;}@Overridepublic int div(int i, int j) {int result = i / j;return result;}}package com.atguigu.spring.aop.xml;import java.util.Arrays;import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;public class LoggingAspect {public void beforeMethod(JoinPoint joinPoint){String methodName = joinPoint.getSignature().getName();Object [] args = joinPoint.getArgs();System.out.println("The method " + methodName + " begins with " + Arrays.asList(args));}public void afterMethod(JoinPoint joinPoint){String methodName = joinPoint.getSignature().getName();System.out.println("The method " + methodName + " ends");}public void afterReturning(JoinPoint joinPoint, Object result){String methodName = joinPoint.getSignature().getName();System.out.println("The method " + methodName + " ends with " + result);}public void afterThrowing(JoinPoint joinPoint, Exception e){String methodName = joinPoint.getSignature().getName();System.out.println("The method " + methodName + " occurs excetion:" + e);}@Around("execution(public int com.atguigu.spring.aop.ArithmeticCalculator.*(..))")public Object aroundMethod(ProceedingJoinPoint pjd){Object result = null;String methodName = pjd.getSignature().getName();try {//前置通知System.out.println("The method " + methodName + " begins with " + Arrays.asList(pjd.getArgs()));//执行目标方法result = pjd.proceed();//返回通知System.out.println("The method " + methodName + " ends with " + result);} catch (Throwable e) {//异常通知System.out.println("The method " + methodName + " occurs exception:" + e);throw new RuntimeException(e);}//后置通知System.out.println("The method " + methodName + " ends");return result;}
}package com.atguigu.spring.aop.xml;import java.util.Arrays;import org.aspectj.lang.JoinPoint;public class VlidationAspect {public void validateArgs(JoinPoint joinPoint){System.out.println("-->validate:" + Arrays.asList(joinPoint.getArgs()));}}package com.atguigu.spring.aop.xml;import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class Main {public static void main(String[] args) {ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-xml.xml");ArithmeticCalculator arithmeticCalculator = (ArithmeticCalculator) ctx.getBean("arithmeticCalculator");System.out.println(arithmeticCalculator.getClass().getName());int result = arithmeticCalculator.add(1, 2);System.out.println("result:" + result);result = arithmeticCalculator.div(1000, 0);System.out.println("result:" + result);}}
<?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.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd"><!-- 配置 bean --><bean id="arithmeticCalculator" class="com.atguigu.spring.aop.xml.ArithmeticCalculatorImpl"></bean><!-- 配置切面的 bean. --><bean id="loggingAspect"class="com.atguigu.spring.aop.xml.LoggingAspect"></bean><bean id="vlidationAspect"class="com.atguigu.spring.aop.xml.VlidationAspect"></bean><!-- 配置 AOP --><aop:config><!-- 配置切点表达式 --><aop:pointcut expression="execution(* com.atguigu.spring.aop.xml.ArithmeticCalculator.*(int, int))" id="pointcut"/><!-- 配置切面及通知 --><aop:aspect ref="loggingAspect" order="2"><aop:before method="beforeMethod" pointcut-ref="pointcut"/><aop:after method="afterMethod" pointcut-ref="pointcut"/><aop:after-throwing method="afterThrowing" pointcut-ref="pointcut" throwing="e"/><aop:after-returning method="afterReturning" pointcut-ref="pointcut" returning="result"/><!--  <aop:around method="aroundMethod" pointcut-ref="pointcut"/>--></aop:aspect>    <aop:aspect ref="vlidationAspect" order="1"><aop:before method="validateArgs" pointcut-ref="pointcut"/></aop:aspect></aop:config></beans>

转载于:https://my.oschina.net/yabushan/blog/691503

SpringAop通知相关推荐

  1. SpringAOP 通知(adivce)- methodIntercepor

    环绕通知(即methodIntercepor) 是SpringAOP 通知模块中的一种通知方式.可用在指定方法执行之前,执行之后.对于同时要实现两种通知的方法是一种便利.若使用BeforeAdivce ...

  2. SpringAOP技术【松思园】

    一.SpringAOP理解 SpringAOP称之为"面向切面编程",这和我们之前编程思想"面向对象编程"是不一样的,当然我们还听过"面向过程的编程& ...

  3. 小汤学编程之JavaEE学习day10——Spring

    一.Spring简介 1.特点     2.核心特性     3.两大核心 二.Spring环境搭建 1.导包     2.准备数据库和表.实体类     3.定义dao层接口和接口映射文件      ...

  4. SpringBoot整合AOP + 自定义注解实现简单的权限验证

    1.简介 主要通过自定义注解,使用SpringAOP的环绕通知拦截请求,判断该方法是否有自定义注解,然后判断该用户是否有该权限,这里做的比较简单. 2.项目搭建 这里是基于SpringBoot的,对于 ...

  5. Spring-AOP的五种通知和切面的优先级、通知变量声明

    SpringAOP的通知分为以下五种: 1前置通知(@before) 在连接点执行之前执行的代码 2后置通知(@after) 在连接点执行之后执行的代码,不管连接点执行后是否出现异常,后置通知都会执行 ...

  6. SpringAOP的几大通知

    首先配置application.xml文件 <?xml version="1.0" encoding="UTF-8"?> <beans xml ...

  7. 跟杨春娟学Spring笔记:AOP之SpringAOP引介通知

    跟杨春娟学Spring笔记:AOP之SpringAOP引介通知 完成:第一遍 1.如何代码实现AOP之SpringAOP引介通知? IntroductionInterceptor(引介通知) 在目标类 ...

  8. springAOP支持的通知类型

    aop的五类通知: 1.前置通知[Before advice]:在连接点前面执行,前置通知不会影响连接点的执行,除非此处抛出异常. 2.正常返回通知[After returning advice]:在 ...

  9. 站内通知 java组件,spring-aop组件详解——Advice通知

    Advice(通知)是面向切面编程中的一个非常重要的概念.我们都知道,AOP的目的在于对目标类或目标方法的逻辑增强(如:日志逻辑.统计逻辑.访问控制逻辑等),那么Advice就代表要增强的具体逻辑.A ...

最新文章

  1. Microbiome:马铃薯疮痂病与土壤微生物组关系新进展
  2. 【二叉查找树BST】二叉查找树的基本操作总结
  3. U3D 代码自动化生成定制预置体的旋转问题
  4. 中国物联网2020年将达到1660亿美元的市场规模
  5. 常见电容器图片_各种电容器图片大集合
  6. 据库中事务、会话、线程这几个概念是什么关系
  7. Linux背后的思想
  8. java 泛型 .net_Java泛型
  9. 51nod 1185 || 51nod 1072 威佐夫博弈
  10. 在线开票服务器设置,开票服务器系统介绍
  11. arkit 人脸捕捉_iPhone X上的ARKit人脸追踪
  12. 【算法学习】1.渐进复杂性
  13. 迪文屏CRC16校验
  14. 微信公众号文章如何设置关键词自动回复链接
  15. 如视VR显示连不上服务器,HTC Vive播放本地视频图文教程(附常见问题解决办法)...
  16. LibVLC —— 本地音视频例子、Qt播放例子
  17. 伽卡他卡电子教室学生端解控代码
  18. word中图片为嵌入式格式时显示不全_“word嵌入式图片不显示的解决办法”的解决方案...
  19. 今日金融词汇--- 商业模式
  20. python 开放_老虎证券开放api的使用python

热门文章

  1. 如何用android下载python_如何在android上运行Python代码
  2. postman 字符串中有冒号_【接口测试】Postman入门09 Postman获取HTTP请求
  3. 第2章[2.1] 开发模式及快速测试方式
  4. Weblogic内存调整
  5. windows 操作系统及相应服务的管理 综合
  6. excel如何做出弧形_人民日报同款海报,只用线和字就能做出高大上的工作报告...
  7. 网页编辑PHP变量,编辑文件中的php代码和变量
  8. 如何做相册_今天才知道,原来长按微信相册,还隐藏着一个实用功能
  9. servlet文件实现弹出框
  10. STM32编译环境、建立工程模板以及程序下载