当前位置: 首页 > news >正文

Spring3系列10- Spring AOP——Pointcut,Advisor拦截指定方法

Spring3系列10- Spring AOP——Pointcut,Advisor

 

  上一篇的Spring AOP Advice例子中,Class(CustomerService)中的全部method都被自动的拦截了。但是大多情况下,你只需要一个方法去拦截一两个method。这样就引入了Pointcut(切入点)的概念,它允许你根据method的名字去拦截指定的method。另外,一个Pointcut必须结合一个Advisor来使用。

 

在Spring AOP中,有3个常用的概念,Advices、Pointcut、Advisor,解释如下,

Advices:表示一个method执行前或执行后的动作。

Pointcut:表示根据method的名字或者正则表达式去拦截一个method。

Advisor:Advice和Pointcut组成的独立的单元,并且能够传给proxy factory 对象。

 

下边来回顾一下上一篇例子中的代码

CustomerService.java

package com.lei.demo.aop.advice;

public class CustomerService {

    private String name;
    private String url;
 
    public void setName(String name) {
        this.name = name;
    }
 
    public void setUrl(String url) {
        this.url = url;
    }
 
    public void printName() {
        System.out.println("Customer name : " + this.name);
    }
 
    public void printURL() {
        System.out.println("Customer website : " + this.url);
    }
 
    public void printThrowException() {
        throw new IllegalArgumentException();
    }

}

 

 配置文件Spring-AOP-Advice.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
    <bean id="customerService" class="com.lei.demo.aop.advice.CustomerService">
        <property name="name" value="LeiOOLei" />
        <property name="url" value="http://www.cnblogs.com/leiOOlei/" />
    </bean>
    
    <bean id="hijackAroundMethodBean" class="com.lei.demo.aop.advice.HijackAroundMethod" />
 
    <bean id="customerServiceProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
        <property name="target" ref="customerService" />
        <property name="interceptorNames">
            <list>
                <value>hijackAroundMethodBean</value>
            </list>
        </property>
    </bean>
 
</beans>

 

HijackAroundMethod.java

package com.lei.demo.aop.advice;

import java.util.Arrays;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

public class HijackAroundMethod implements MethodInterceptor {

    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        System.out.println("Method name : "
                + methodInvocation.getMethod().getName());
        System.out.println("Method arguments : "
                + Arrays.toString(methodInvocation.getArguments()));
 
        // 相当于  MethodBeforeAdvice
        System.out.println("HijackAroundMethod : Before method hijacked!");
 
        try {
            // 调用原方法,即调用CustomerService中的方法
            Object result = methodInvocation.proceed();
 
            // 相当于 AfterReturningAdvice
            System.out.println("HijackAroundMethod : After method hijacked!");
 
            return result;
 
        } catch (IllegalArgumentException e) {
            // 相当于 ThrowsAdvice
            System.out.println("HijackAroundMethod : Throw exception hijacked!");
            throw e;
        }
    }

}

 

运行如下App.java

package com.lei.demo.aop.advice;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {

    public static void main(String[] args) {
        ApplicationContext appContext = new ClassPathXmlApplicationContext(
                new String[] { "Spring-AOP-Advice.xml" });

        
        System.out.println("使用Spring AOP 如下");
        CustomerService cust = (CustomerService) appContext.getBean("customerServiceProxy");
        System.out.println("*************************");
        cust.printName();
        System.out.println("*************************");
        cust.printURL();
        System.out.println("*************************");
        
        try {
            cust.printThrowException();
        } catch (Exception e) {
 
        }
 
    }

}

 

 运行结果:

使用Spring AOP 如下

*************************

Method name : printName

Method arguments : []

HijackAroundMethod : Before method hijacked!

Customer name : LeiOOLei

HijackAroundMethod : After method hijacked!

*************************

Method name : printURL

Method arguments : []

HijackAroundMethod : Before method hijacked!

Customer website : http://www.cnblogs.com/leiOOlei/

HijackAroundMethod : After method hijacked!

*************************

Method name : printThrowException

Method arguments : []

HijackAroundMethod : Before method hijacked!

HijackAroundMethod : Throw exception hijacked!

 

上边的结果中,CustomerService.java中,全部的method方法全部被拦截了,下边我们将展示怎样利用Pointcuts只拦截printName()。

 

你可以用名字匹配法和正则表达式匹配法去匹配要拦截的method。

1.      Pointcut——Name match example

通过pointcut和advisor拦截printName()方法。

创建一个NameMatchMethodPointcut的bean,将你想拦截的方法的名字printName注入到属性mappedName,如下

<bean id="customerPointcut"
        class="org.springframework.aop.support.NameMatchMethodPointcut">
        <property name="mappedName" value="printName" />
</bean>

 

 创建一个DefaultPointcutAdvisor的advisor bean,将pointcut和advice关联起来。

<bean id="customerAdvisor"
        class="org.springframework.aop.support.DefaultPointcutAdvisor">
        <property name="pointcut" ref="customerPointcut" />
        <property name="advice" ref=" hijackAroundMethodBean " />
</bean>

 

更改代理的interceptorNames值,将上边的advisor( customerAdvisor)替代原来的hijackAroundMethodBean。

<bean id="customerServiceProxy"
        class="org.springframework.aop.framework.ProxyFactoryBean">
 
        <property name="target" ref="customerService" />
 
        <property name="interceptorNames">
            <list>
                <value>customerAdvisor</value>
            </list>
        </property>
</bean>

 

所有的配置文件如下:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
    <bean id="customerService" class="com.lei.demo.aop.advice.CustomerService">
        <property name="name" value="LeiOOLei" />
        <property name="url" value="http://www.cnblogs.com/leiOOlei/" />
    </bean>
 
    <bean id="hijackAroundMethodBean" class="com.lei.demo.aop.advice.HijackAroundMethod" />
 
    <bean id="customerServiceProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
 
        <property name="target" ref="customerService" />
 
        <property name="interceptorNames">
            <list>
                <value>customerAdvisor</value>
            </list>
        </property>
    </bean>
 
    <bean id="customerPointcut"class="org.springframework.aop.support.NameMatchMethodPointcut">
        <property name="mappedName" value="printName" />
    </bean>
 
    <bean id="customerAdvisor" class="org.springframework.aop.support.DefaultPointcutAdvisor">
        <property name="pointcut" ref="customerPointcut" />
        <property name="advice" ref=" hijackAroundMethodBean " />
    </bean>
 
</beans>

 

 再运行一下App.java,输出结果如下:

使用Spring AOP 如下

*************************

Method name : printName

Method arguments : []

HijackAroundMethod : Before method hijacked!

Customer name : LeiOOLei

HijackAroundMethod : After method hijacked!

*************************

Customer website : http://www.cnblogs.com/leiOOlei/

*************************

 

以上运行结果显示,只拦截了printName()方法。

 

注意:

以上配置中pointcut和advisor可以合并在一起配置,即不用单独配置customerPointcutcustomerAdvisor,只要配置customerAdvisor时class选择NameMatchMethodPointcutAdvisor如下:

<bean id="customerAdvisor" class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor">
        <property name="mappedName" value="printName" />
        <property name="advice" ref="hijackAroundMethodBean" />
</bean>

 

这样,整个配置文件如下:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
    <bean id="customerService" class="com.lei.demo.aop.advice.CustomerService">
        <property name="name" value="LeiOOLei" />
        <property name="url" value="http://www.cnblogs.com/leiOOlei/" />
    </bean>
    
    <bean id="hijackAroundMethodBean" class="com.lei.demo.aop.advice.HijackAroundMethod" />
 
    <bean id="customerServiceProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
        <property name="target" ref="customerService" />
        <property name="interceptorNames">
            <list>
                <value>customerAdvisor</value>
            </list>
        </property>
    </bean>
    
    
    <bean id="customerAdvisor" class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor">
        <property name="mappedName" value="printName" />
        <property name="advice" ref="hijackAroundMethodBean" />
    </bean>
 
</beans>

 

  实际上这种做法将method名字与具体的advice捆绑在一起,有悖于Spring松耦合理念,如果将method名字单独配置成pointcut(切入点),advice和pointcut的结合会更灵活,使一个pointcut可以和多个advice结合。

2.      Pointcut——Regular exxpression match example

你可以配置用正则表达式匹配需要拦截的method,如下配置

<bean id="customerAdvisor" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
        <property name="patterns">
            <list>
                <value>.*URL.*</value>
            </list>
        </property>
        <property name="advice" ref="hijackAroundMethodBeanAdvice" />
    </bean>

 

现在,你可以拦截名字中包含URL字符的method了,在实际工作中,你可以用它来管理DAO层,例如,你可以用“.*DAO.*”来拦截所有DAO层中的相关业务。

 

 

 

 

 

相关文章:

  • 使用升腾linux瘦客户机连接xendesktop实现USB KEY映射时,需要修改的文件。
  • 图解Team Foundation Server 2013系列
  • 制作 Windows 8.1 ADK 离线安装包
  • AsyncTask异步加载跟listview的结合
  • Raphael入门实例:动画与箭头
  • Activity加载模式
  • Ubuntu下Alt+Tab快捷键不能用解决办法
  • Google Scholar 论文参考文献的自动生成
  • discuz X2.5自己写代码,获取当前登录的用户信息
  • 通过搭建一个精简的C语言开发环境了解一个C程序的执行过程
  • 【javascript基础】系列
  • 产品需求文档的写作(一) – 写前准备(信息结构图)
  • 【Nodejs开发】第1章 述与环境搭建
  • 在管理实际中,心态很重要,当你以欣赏的态度去看一件事,你便会看到许多优点,以批评的态度,你便会看到无数缺点。...
  • linux上未分区硬盘的格式化实践
  • 【跃迁之路】【519天】程序员高效学习方法论探索系列(实验阶段276-2018.07.09)...
  • 2017 年终总结 —— 在路上
  • Angular 响应式表单之下拉框
  • Apache Zeppelin在Apache Trafodion上的可视化
  • create-react-app做的留言板
  • express + mock 让前后台并行开发
  • js数组之filter
  • Python socket服务器端、客户端传送信息
  • spring boot 整合mybatis 无法输出sql的问题
  • Twitter赢在开放,三年创造奇迹
  • Vue实战(四)登录/注册页的实现
  • 离散点最小(凸)包围边界查找
  • 前端
  • 如何解决微信端直接跳WAP端
  • 如何借助 NoSQL 提高 JPA 应用性能
  • 什么是Javascript函数节流?
  • 实战|智能家居行业移动应用性能分析
  • 使用 Xcode 的 Target 区分开发和生产环境
  • 问:在指定的JSON数据中(最外层是数组)根据指定条件拿到匹配到的结果
  • 与 ConTeXt MkIV 官方文档的接驳
  • 在 Chrome DevTools 中调试 JavaScript 入门
  • MiKTeX could not find the script engine ‘perl.exe‘ which is required to execute ‘latexmk‘.
  • puppet连载22:define用法
  • scrapy中间件源码分析及常用中间件大全
  • 阿里云IoT边缘计算助力企业零改造实现远程运维 ...
  • ​ArcGIS Pro 如何批量删除字段
  • ​LeetCode解法汇总2304. 网格中的最小路径代价
  • ​力扣解法汇总1802. 有界数组中指定下标处的最大值
  • #git 撤消对文件的更改
  • (11)MSP430F5529 定时器B
  • (2)(2.4) TerraRanger Tower/Tower EVO(360度)
  • (4) PIVOT 和 UPIVOT 的使用
  • (ISPRS,2023)深度语义-视觉对齐用于zero-shot遥感图像场景分类
  • (Redis使用系列) SpringBoot中Redis的RedisConfig 二
  • (八)光盘的挂载与解挂、挂载CentOS镜像、rpm安装软件详细学习笔记
  • (翻译)terry crowley: 写给程序员
  • (附源码)ssm智慧社区管理系统 毕业设计 101635
  • (力扣记录)1448. 统计二叉树中好节点的数目
  • (免费领源码)python#django#mysql公交线路查询系统85021- 计算机毕业设计项目选题推荐
  • (十六)串口UART