Spring AOP Example – Advice

Spring AOP + AspectJ annotation example NULL 博文链接:https://tuoxinquyu.iteye.com/blog/1465187 立即下载

我们知道Spring有两个重要的特性:IOC和AOP ,大学期间只是对Spring有一个粗浅的认识,认为spring就是配置类,建立bean,然后就可以调用类的方法。直到慢慢了解才知道Spring还有很深的东西,Spring的强大。

        这篇博文主要讲述Spring AOP 的 hijack(拦截) 功能,主要描述为当我们在执行一个类的方法的时候我们可以在方法执行前和执行后增加额外的方法

        原文就是 Spring AOP can hijack the executing method,and add extra functionality before or after the method execution

     我们先声明一个实体类,CustomerService

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.kwe.bean;                                                                                                                                     /** 
  2.  * bean 
  3.  * @author rey.yang 
  4.  * 
  5.  */  
  6. public class CustomerService {  
  7.     private String name;  
  8.     private String url;  
  9.    
  10.     public void setName(String name) {  
  11.         this.name = name;  
  12.     }  
  13.     public void setUrl(String url) {  
  14.         this.url = url;  
  15.     }  
  16.     public void printName() {  
  17.         System.out.println("Customer name : " + this.name);  
  18.     }  
  19.     public void printURL() {  
  20.         System.out.println("Customer website : " + this.url);  
  21.     }  
  22.     public void printThrowException() {  
  23.         throw new IllegalArgumentException();  
  24.     }  
  25. }  
   项目的目录大致是这样的:


   配置文件spring-customer.xml 放在src的根目录下:

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xsi:schemaLocation="http://www.springframework.org/schema/beans  
  5.     http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">  
  6.       
  7.       
  8.       
  9.     <bean id="customerService" class="com.kwe.bean.CustomerService">  
  10.         <property name="name" value="yang yang"></property>  
  11.         <property name="url" value="http://www.youkuaiyun.com"></property>  
  12.     </bean>  
  13. </beans>  

          测试配置是否OK?

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public class App {  
  2.     public static void main(String[] args) {  
  3.         ApplicationContext appContext = new ClassPathXmlApplicationContext(  
  4.                 new String[] { "spring-customer.xml" });  
  5.    
  6.         CustomerService cust = (CustomerService) appContext.getBean("customerService");  
  7.    
  8.         System.out.println("*************************");  
  9.         cust.printName();  
  10.         System.out.println("*************************");  
  11.         cust.printURL();  
  12.         System.out.println("*************************");  
  13.         try {  
  14.             cust.printThrowException();  
  15.         } catch (Exception e) {  
  16.         }  
  17.     }  
  18. }  

         输出如下:

        

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. *************************  
  2. Customer name : yang yang  
  3. *************************  
  4. Customer website : http://www.youkuaiyun.com  
  5. *************************  

        我们建立一个拦截类HijackBeforeMethod继承MethodBeforeAdvice

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public class HijackBeforeMethod implements MethodBeforeAdvice{  
  2.   
  3.     @Override  
  4.     public void before(Method method, Object[] args, Object target)  
  5.             throws Throwable {  
  6.         System.out.println("HijackBeforeMethod:Before method hijack");  
  7.     }         
  8. }     

       然后在spring-customer2.xml下配置:
[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <bean id="customerService" class="com.kwe.bean.CustomerService">  
  2.     <property name="name" value="yang yang"></property>  
  3.     <property name="url" value="http://www.youkuaiyun.com"></property>  
  4. </bean>  
  5.   
  6. <bean id="hijackBeforeMethod" class="com.kwe.hijack.HijackBeforeMethod"></bean>  
  7.   
  8. <bean id="customerServiceProxy" class="org.springframework.aop.framework.ProxyFactoryBean">  
  9.     <!-- target define which bean you want to hijack -->  
  10.     <property name="target" ref="customerService"></property>  
  11.       
  12.     <!-- interceptorNames define which class(advice) you want to apply on this proxy/target object -->  
  13.     <property name="interceptorNames">  
  14.         <list>  
  15.             <value>hijackBeforeMethod</value>  
  16.         </list>  
  17.     </property>  
  18. </bean>  
         这里解释一下<property name="target" ref = "customerService"></property>   代表要拦截的类是customerService

         <property name="interceptorNames"> 中 <value>hijackBeforeMethod</value>代表基于customerService拦截类的是HijackBeforeMethod

        执行一下App(把配置文件改成spring-customer2.xml和相关bean),

        

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public class App2 {  
  2.     public static void main(String[] args) {  
  3.         ApplicationContext appContext = new ClassPathXmlApplicationContext(  
  4.                 new String[] { "spring-customer2.xml" });  
  5.    
  6.         CustomerService cust =   
  7.                                 (CustomerService) appContext.getBean("customerServiceProxy");  
  8.    
  9.         System.out.println("*************************");  
  10.         cust.printName();  
  11.         System.out.println("*************************");  
  12.         cust.printURL();  
  13.         System.out.println("*************************");  
  14.         try {  
  15.             cust.printThrowException();  
  16.         } catch (Exception e) {  
  17.         }  
  18.     }  
  19. }  

        输出为:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. *************************  
  2. HijackBeforeMethod:Before method hijack  
  3. Customer name : yang yang  
  4. *************************  
  5. HijackBeforeMethod:Before method hijack  
  6. Customer website : http://www.youkuaiyun.com  
  7. *************************  
  8. HijackBeforeMethod:Before method hijack  
        我们可以看到它在每个方法的前面都做了一个拦截。

        同理,我们想在实体类的方法完成之后再进行操作,则我们可以建立一个HijackAfterMethod实现AfterReturningAdvice类:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public class HijackAfterMethod implements AfterReturningAdvice{  
  2.     @Override  
  3.     public void afterReturning(Object returnValue, Method method, Object[] args,  
  4.             Object target) throws Throwable {  
  5.         System.out.println("HijackAfterMethod: After method hijacked!");  
  6.     }  
  7. }  

        在配置文件中进行相关配置,略微改变一点即可:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <bean id="customerServiceProxy" class="org.springframework.aop.framework.ProxyFactoryBean">  
  2.     <!-- target define which bean you want to hijack -->  
  3.     <property name="target" ref="customerService"></property>  
  4.       
  5.     <!-- interceptorNames define which class(advice) you want to apply on this proxy/target object -->  
  6.     <property name="interceptorNames">  
  7.         <list>  
  8.             <value>hijackAfterMethod</value>  
  9.         </list>  
  10.     </property>  
  11. </bean>  
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public class App3 {  
  2.     public static void main(String[] args) {  
  3.         ApplicationContext appContext = new ClassPathXmlApplicationContext(  
  4.                 new String[] { "spring-customer3.xml" });  
  5.    
  6.         CustomerService cust =   
  7.                                 (CustomerService) appContext.getBean("customerServiceProxy");  
  8.    
  9.         System.out.println("*************************");  
  10.         cust.printName();  
  11.         System.out.println("*************************");  
  12.         cust.printURL();  
  13.         System.out.println("*************************");  
  14.         try {  
  15.             cust.printThrowException();  
  16.         } catch (Exception e) {  
  17.         }  
  18.     }  
  19. }  

        执行一下,得到:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. *************************  
  2. Customer name : yang yang  
  3. HijackAfterMethod: After method hijacked!  
  4. *************************  
  5. Customer website : http://www.baidu.com  
  6. HijackAfterMethod: After method hijacked!  
  7. *************************  
        
       另外我们想拦截捕获的异常,则可以建立一个HijackThrowException实现ThrowsAdvice接口

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public class HijackThrowException implements ThrowsAdvice{  
  2.     public void afterThrowing(IllegalArgumentException e) throws Throwable{  
  3.         System.out.println("HijackThrowException:Throw exception hijacked");  
  4.     }  
  5. }  

       配置文件如上,只修改关键字段名字即可,主类的方法也是一样,执行一下看到,在抛出异常的时候就对方法进行了拦截。

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. *************************  
  2. Customer name : yang yang  
  3. *************************  
  4. Customer website : http://www.baidu.com  
  5. *************************  
  6. HijackThrowException:Throw exception hijacked  
  

        那么我们想对实体类方法执行前和执行后进行拦截,我们要怎么办? ,这个稍微要复杂些....

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.  * 集合了方法拦截前后和异常的拦截 
  3.  * @author rey.yang 
  4.  * 
  5.  */  
  6. public class HijackAroundMethod implements MethodInterceptor{  
  7.     @Override  
  8.     public Object invoke(MethodInvocation methodInvocation) throws Throwable {  
  9.         /** 
  10.          * 相当于反射获取方法的名称 
  11.          * 方法的参数 
  12.          */  
  13.         System.out.println("Method name:"+methodInvocation.getMethod().getName());  
  14.         System.out.println("Method arguments:"+Arrays.toString(methodInvocation.getArguments()));  
  15.         //same with MethodBeforeAdvice  
  16.         System.out.println("HijackAroundMethod:Before method hijacked!");  
  17.         try {  
  18.             //proceed to original method call  
  19.             Object result = methodInvocation.proceed();  
  20.             //same with AfterReturningAdvice  
  21.             System.out.println("HijackAroundMethod:Before after hijacked!");  
  22.             return result;  
  23.         } catch (IllegalArgumentException e) {  
  24.             //same with ThrowAdvice  
  25.             System.out.println("HijackArounMethod:Throw exception hijacked!");  
  26.             throw e;  
  27.         }  
  28.     }  
  29. }  

        


        配置文件如下:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1.        <bean id="hijackAroundMethodBean" class="com.kwe.hijack.HijackAroundMethod"></bean>  
  2.   
  3. <bean id="customerServiceProxy" class="org.springframework.aop.framework.ProxyFactoryBean">  
  4.     <!-- target define which bean you want to hijack -->  
  5.     <property name="target" ref="customerService"></property>  
  6.       
  7.     <!-- interceptorNames define which class(advice) you want to apply on this proxy/target object -->  
  8.     <property name="interceptorNames">  
  9.         <list>  
  10.             <value>hijackAroundMethodBean</value>  
  11.         </list>  
  12.     </property>  
  13. </bean>  

        执行一下得到

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. *************************  
  2. Method name:printName  
  3. Method arguments:[]  
  4. HijackAroundMethod:Before method hijacked!  
  5. Customer name : yang yang  
  6. HijackAroundMethod:Before after hijacked!  
  7. *************************  
  8. Method name:printURL  
  9. Method arguments:[]  
  10. HijackAroundMethod:Before method hijacked!  
  11. Customer website : http://www.baidu.com  
  12. HijackAroundMethod:Before after hijacked!  
  13. *************************  
  14. Method name:printThrowException  
  15. Method arguments:[]  
  16. HijackAroundMethod:Before method hijacked!  
  17. HijackArounMethod:Throw exception hijacked!  

          在Spring AOP中,应该掌握三种配置方法:Advice,Poingcut,Advisor ,上面的例子是Advice方式进行对方法的拦截。我们可以根据相应的需求进行对应的实现。

          原文链接:http://www.mkyong.com/spring/spring-aop-examples-advice/


http://blog.youkuaiyun.com/pearyangyang/article/details/45053913

Spring AOP Example – Pointcut , Advisor NULL 博文链接:https://tuoxinquyu.iteye.com/blog/1465200 立即下载

相关推荐

从硬件拆解到图像生成:一次搞懂MRI设备(主磁体、梯度线圈、射频系统)是如何协同工作的

本文深入解析MRI设备的三大核心系统——主磁体、梯度线圈和射频系统如何协同工作,实现从量子现象到诊断图像的转化。通过详细的技术参数和临床案例,揭示磁共振成像(MRI)在医疗图像处理中的精密工程原理和最新技术突破,帮助读者全面理解这一现代医学影像技术的运作机制。

weixin_33734785的博客 549

Spring AOP示例

官方文档:7.Aspect Oriented Programming with Spring spring aop像一个拦截器,可以对被拦截的方法(join point)做增强处理,而且对连接点无代码入侵。在使用aop编程时,先分析业务以便定义PointCut,然后定义切面类和advice。示例如下: 连接点所在的类: package com.example.demo.aopdemo; import org.springframework.web.bind.annotation.GetMapp..

u011183517的专栏 668

国产谷歌地球,地形分析秒杀同款地图软件

咱们做地质、林业、水文、水利、电力、GIS、地图、水保、环境的,需要经常用到各种数据,比如影像、地形、矢量、模型等,但目前80%的规划大数据展示都离不开ArcGIS,令人头大的是很多朋友连ArcGIS软件安装起来都费劲。。。 那不会ArcGIS又装不了Google Earth怎么开展工作? 今天推荐大家一款国产免费专业地图浏览下载测量分析神器—图新地球 图新地球,国产三维gis软件。可以查看高清卫星影像地形以及其他很多常用电子地图,对地图需求的掌握远胜过Google Maps,而且上手比国外软件要简单

GISWorld3D的博客 3685

Spring AOP Example Tutorial

这是一篇翻译,原文:Spring AOP Example Tutorial – Aspect, Advice, Pointcut, JoinPoint, Annotations, XML Configuration Spring 框架发展出了两个核心概念:依赖注入和面向切面编程(AOP)。我们已经了解了Spring 的依赖注入是如何实现的,今天...

weixin_34355881的博客 180

自考计算机系统原理(第六章计算机系统概论)-13015

名词解释 I/O 硬件 I/O软件 用户空间I/O软件 内核空间I/O 软件 系统调用处理程序 系统调用服务例程 设备驱动程序 中断服务程序 系统级1/O函数 虚拟文件系统 文件描述符 文件元数据 流缓冲区 索引节点 目录文件 目录项 系统打开文件表 磁盘高速缓存 高速缓存 RAM I / O 控制方式 程序直接控制I/O 就绪状态 中断控制I/O 中断屏蔽字 多重中断 中断嵌套 DMA 方式 DMA 控制器 设备控制器 I/O端口 控制端口 数据端口 状态端口 I/O 地址空间 独立编址方式 统一编址方

qq_23872947的博客 1150

ROS2机械臂MPC轨迹规划实战:从MoveIt 2插件配置到参数调优全流程

本文详细介绍了ROS2机械臂MPC轨迹规划的全流程,从MoveIt 2插件配置到参数调优。通过模型预测控制(MPC)技术,实现高精度运动控制,特别适合复杂装配任务。文章包含环境搭建、插件部署、参数设计及实战调优方法,帮助开发者快速掌握ROS2机械臂的MPC轨迹规划技术。

i0j1k2l3m的博客 206

Spring AOP(面向切面)介绍以及示例(@Before @Around @After @AfterReturning @AfrerThrowing)

1、什么是面向切面(AOP) 在使用面向切面之前我们要理解一下面向对象和面向切面这两个概念。 面向对象就是提取公共特征进行抽象化,比如,不管是男人还是女人,它们都有年龄、名字等属性,那么就可以把这些属性以及相同的方法(如get、set)抽取到父类中,是一种纵向的抽取。 面向切面,就是将一些逻辑通过横向切割的方式抽取到一个独立的模块,业务只需要关注自身的逻辑,在运行业务时,由程序将这些逻辑织入,是一种横向的抽取。比如假设数据库操作之前需要编写日志,这时可以对修改每个函数添加写日志操作,为了提升代码复用可以进

qq_37130607的博客 4205

保姆级教程:用GEE(Google Earth Engine)复现CASA模型计算NPP,附完整数据集清单与Python代码

本文提供了一份详细的保姆级教程,指导如何使用GEE(Google Earth Engine)复现CASA模型计算NPP(净初级生产力)。教程涵盖环境准备、关键数据集获取与处理、Python代码实现全流程,以及结果验证与常见问题解决方案,帮助生态学研究者高效完成NPP计算。

weixin_28707365的博客 334

spring aop示例_Spring批处理示例

spring aop示例Welcome to Spring Batch Example. Spring Batch is a spring framework module for execution of batch job. We can use spring batch to process a series of jobs. 欢迎使用Spring Batch示例。 Spring Batch...

从零开始的教程世界 332

【Nginx学习】5步揭秘Nginx邮件代理模块:邮件代理服务器的功能与实现

Nginx的邮件代理模块(Mail Proxy Module)允许Nginx作为邮件代理服务器,支持SMTP、POP3和IMAP协议。这使得Nginx可以作为一个高性能的邮件网关,用于过滤垃圾邮件、病毒扫描、负载均衡等任务。简单来说,Nginx在这里就像是一个邮递员,负责将邮件从发件人手中安全、快速地送到收件人手中。通过上述的解析,我们可以看到Nginx在邮件代理模块中的设计和实现。从配置解析、连接处理,到协议处理、SSL/TLS加密和日志记录,每一步都至关重要。

java专栏 1314

如何解除“无法完成操作 因为文件包含病毒或潜在垃圾软件”

当运行软件遇到“无法完成操作 因为文件包含病毒或潜在垃圾软件”时,如何解决?控制面板-系统和安全-Windows Defender防火墙-自定义设置,将专用网络及公用网络关闭。点击后,选择“病毒和威胁防护”-管理配置。进入安全中心后,选择“病毒和威胁防护”将需要排斥的选项输入后,保存配置即可。2:打开windows安全中心。

笔者从事电信媒体开发多年,愿意将多年的开发经验分享给同行 6万+

Spring AOP Example Tutorial – Aspect, Advice, Pointcut, JoinPoint, Annotations, XML Configuration

Spring Framework is developed on two core concepts – Dependency Injection and Aspect Oriented Programming (AOP). Aspect Oriented Programming OverviewMost of the enterprise applications have some common

1058

VTK API 详解(103):vtkGPUVolumeRayCastMapper - GPU加速体绘制

是 VTK 中基于 GPU 的高效体绘制映射器,利用现代显卡的计算能力,通过射线投射算法实现快速且高质量的三维体积渲染。相比 CPU 版本的,GPU 映射器性能大幅提升,支持更复杂的光照和渲染效果,是体绘制的主流选择。是 VTK 中性能优异的GPU体绘制映射器;适合大数据集和实时交互应用;配合灵活设置颜色、透明度和光照;建议在支持OpenGL的环境中使用。

yumeiguo的博客 295

Spring AOP Advice - Pointcuts – Name match example

Last few pages talked about spring advices (before advice, after return advice and around advice). The disadvantages of these are, these advices will intercept all available methods. What if we want to

qq_31230529的博客 353

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

Spring AOP Advice - Pointcuts – Regular expression example

Last few pages talked about spring advices (before advice, after return advice and around advice). The disadvantages of these are, these advices will intercept all available methods. What if we want to

qq_31230529的博客 441

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

Spring AOP Example

Spring AOP (Aspect-oriented programming) framework is used to modularize cross-cutting concerns in aspects. Put it simple, it’s just an interceptor to intercept some processes, for example, when a met

贾亮的专栏 605

HowToDoInJava----Java concurrency – CountDownLatch Example

HowToDoInJava Java concurrency – CountDownLatch Example https://howtodoinjava.com/java/multi-threading/when-to-use-countdownlatch-java-concurrency-example-tutorial/ Spring AOP Tutorial Example htt...

LTCM_SAKURA的博客 333

springmvc

三层架构表现层: 接收请求响应用户 servlet – springMVC业务层:处理业务,事务 自己写业务层 – spring 管理业务层持久层: 对数据库进行增删改查操作 jdbc – dbutils --jdbcTemplate – mybatis – spring dataMVC设计模式M:model 模型:封装数据 广义:业务模型层 = dao + service + domainV:view 视图:展示数据 广义:能展示数据都是视图:jsp, html ,pdf ,f

梦想是很难很难的,所以先勇敢一点 575

SSM SpringBoot

Maven 是一款为 Java 项目构建管理、依赖管理的工具(软件),使用 Maven 可以自动化构建、测试、打包和发布项目,大大提高了开发效率和质量。总结:Maven就是一个软件,掌握软件安装、配置、以及基本功能(项目构建、依赖管理)使用就是本课程的主要目标!

钟佩颖的学习 717

工作中使用到的单词(软件开发)

1.エイリアス   alias 别名 powershell使用 get-help 命令时,会得到与此命令 相关(别名)的命令 2.プロキシ proxy 代 理 3.プロモート   promote 促进,提升   开发的系统新功能上线发布,有时会使用到这个词,比如 STプロモート 还有使用リリース这个词的。比如STリリース。个人认为两者含义相同。 4.見逃し み................................................................

sun0322 6万+

3.3 AOP之AOP概念及相关术语

AOP(Aspect Oriented Programming)是一种设计思想,是软件设计领域中的面向切面编程,它是面向对象编程的一种补充和完善,它以通过预编译方式和运行期动态代理方式实现在不修改源代码的情况下给程序动态统一添加额外功能的一种技术。...

qq_44774198的博客 426
上一篇: 欢迎使用优快云-markdown编辑器
下一篇: 正则表达式30分钟入门教程
ComputerRookie
博客等级 码龄15年 5粉丝 6原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值