Spring面向切面编程

Spring提供了4种类型的AOP支持:

  • 基于代理的经典Spring AOP;
  • 纯POJO切面;
  • @AspectJ注解驱动的切面;
  • 注入式AspectJ切面(适用于Spring各版本)

因为Spring基于动态代理,所以Spring只支持方法连接点。这与一些其他的AOP框架是不同的,例如AspectJ和JBoss,除了方法切点,它们还提供了字段和构造器接入点。

一、定义切点

在Spring AOP中,要使用AspectJ的切点表达式语言来定义切点。以下是AspectJ切点指示器:

  • arg(),限制连接点匹配参数为指定类型的执行方法
  • @args(),限制连接点匹配参数由指定注解标注的执行方法
  • execution(),用于匹配是连接点的执行方法
  • target,限制连接点匹配目标对象为指定类型的类
  • @target(),限制连接点匹配特定的执行对象,这些对象对应的类要具有指定类型的注解
  • within(),限制连接点匹配指定的类型
  • @within(),限制连接点匹配指定注解所标注的类型(当使用Spring AOP时,方法定义在由指定的注解所标注的类里)
  • @annotation,限定匹配带有指定注解的连接点

只有execution指示器是实际执行匹配的,而其他的指示器都是用来限制匹配的。

切点表达式,这个表达式能够设置当perform()方 法执行时触发通知的调用

方法表达式以“*”号开始,表明了我们不关心方法返回值的类型。然后,我们指定了全限定类名和方法名。对于方法参数列表,我们使用两个点号(..)表明切点要选择任意的perform()方法,无论该方法的入参是什么。

1.用法:

execution( * concert.Performance.perform(..)) 

2.包含条件时怎么表示呢?

execution( * concert.Performance.perform(..))  && within(concert.*) //表示同时满足

因为“&”在XML中有特殊含义,所以在Spring的XML配置里面描述切点时,我们可以使用and来代替“&&”。同样,or 和not可以分别用来代替“||”和“!”。

3.Spring还引入了一个新的bean()指示器,它允许我们在切点表达式中使用bean的ID来标识bean。bean()使用bean ID或bean名称作为参数来限制切点只匹配特定的bean。:

execution( * concert.Performance.perform(..))  and bean("user") //表示同时满足

我们还可以使用非操作为除了特定ID以外的其他bean应用通知:

execution( * concert.Performance.perform(..))  and  !bean("user") //表示同时满足

在此场景下,切面的通知会被编织到所有ID不为woodstock的bean中。

二、使用注解创建切面

AspectJ提供了五个注解来定义通知(要实现的切面):

  • @After :通知方法会在目标方法返回或抛出异常后调用。
  • @AfterReturning : 通知方法会在目标方法返回后调用。
  • @AfterThrowing :通知方法会在目标方法抛出异常后调用。
  • @Around : 通知方法会将目标方法封装起来。
  • @Before : 通知方法会在目标方法调用之前执行。
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;

@Aspect
public class Audience {
    
    @Before("execution(* com.df.test.service.impl.CDPlayer.play(..))")
    public void beforeAction(){
        System.out.println("beforeAction");
    }
    
    @After("execution(* com.df.test.service.impl.CDPlayer.play(..))")
    public void afterAction(){
        System.out.println("afterAction");
    }

    
    @AfterReturning("execution(* com.df.test.service.impl.CDPlayer.play(..))")
    public void afterReturningAction(){
        System.out.println("afterReturningAction");
    }

    
    @AfterThrowing("execution(* com.df.test.service.impl.CDPlayer.play(..))")
    public void afterThrowingAction(){
        System.out.println("afterThrowingAction");
    }

}

我们完全可以这样做:@Pointcut注解能够在一个@AspectJ切面内定义可重用的切点,从而减少代码的重复量。

package com.df.test.service.impl;

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;


@Aspect
public class Audience {
    
    @Pointcut("execution(* com.df.test.service.impl.CDPlayer.play(..))")
    public void Action(){
        
    }
    
    @Before("Action()")
    public void beforeAction(){
        System.out.println("beforeAction");
    }
    
    @After("Action()")
    public void afterAction(){
        System.out.println("afterAction");
    }

    
    @AfterReturning("Action()")
    public void afterReturningAction(){
        System.out.println("afterReturningAction");
    }

    
    @AfterThrowing("Action()")
    public void afterThrowingAction(){
        System.out.println("afterThrowingAction");
    }

}

光有切面和切点是不够了,连接点(一个很基础的类CDPlayer,包含play方法)这里就不展示了。还要讲切面注入到Spring容器中去,并使用@EnableAspectJAutoProxy 注解,表示启用自动代理功能,xml用<aop:aspectj-autoproxy>来启用自动代理功能。


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@Configuration
@ComponentScan(basePackageClasses = {SgtPeppers.class})
@EnableAspectJAutoProxy   // 启用自动代理功能
public class CDPlayerConfig {   
    
    @Bean
    public Audience getAd(){
        return new Audience();
    }
}

当然,我们也可以使用@Around环绕通知,就可以代替以上所有通知能干的事情:

...
import org.aspectj.lang.ProceedingJoinPoint;

@Aspect
public class Audience {
    
    @Pointcut("execution(* com.df.test.service.impl.CDPlayer.play(..))")
    public void Action(){
        
    }

    @Around("Action()")
    public void aroundAction(ProceedingJoinPoint jp) { //必须要这个参数
        
        try {
            System.out.println("beforeAction");
            jp.proceed(); //执行连接点的方法,也就是play()方法
            System.out.println("afterAction");
            
        } catch (Throwable e) {
            // TODO Auto-generated catch block
            System.out.println("afterThrowingAction");
            e.printStackTrace();
        }
    }
}

有时候我们要拦截参数,做一些其他操作,可以这样完成:

package com.df.test.service.impl;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;


@Aspect
public class Audience {
    
    @Pointcut("execution(* com.df.test.service.impl.CDPlayer.play(..))")
    public void Action(){
        
    }
    
    //可能在切点被执行之前,需要对传入的参数进行处理
    @Before("Action() && args(prams3)")
    public void beforeAction(String prams3){  //args(prams3)参数名称必须与形参保持一致
        System.out.println("beforeAction" + prams3);
        System.out.println("beforeAction");
    }
    
    @After("Action()")
    public void afterAction(){
        System.out.println("afterAction");
    }

    //对结果进行处理。ps:这里本人实现时,result一直是null,暂时没弄清楚原因,知道的同学请不吝赐教
    @AfterReturning(pointcut = "Action()" ,returning = "result")
    public void afterReturningAction(String result){  //returning = "result",名称要与形参保持一致
        System.out.println("afterReturningAction" + result);
    }

    //要是跑异常,可以拦截起来做处理
    @AfterThrowing(pointcut = "Action()" ,throwing = "e")
    public void afterThrowingAction(Exception e){
        System.out.println("afterThrowingAction" +e.getMessage());
    }

}

SpringAOP的基本使用,到这里已经完成了。后面将会继续探讨通过AOP思想所引入的新功能以及AspectJ的使用。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,830评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,992评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,875评论 0 331
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,837评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,734评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,091评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,550评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,217评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,368评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,298评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,350评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,027评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,623评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,706评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,940评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,349评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,936评论 2 341

推荐阅读更多精彩内容

  • 本章内容: 面向切面编程的基本原理 通过POJO创建切面 使用@AspectJ注解 为AspectJ切面注入依赖 ...
    谢随安阅读 3,115评论 0 9
  • AOP,也就是面向方面编程或者说面向面编程,是一种很重要的思想。在企业级系统中经常需要打印日志、事务管理这样针对某...
    乐百川阅读 886评论 0 8
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,566评论 18 139
  • 曰:“尊德乐义,则可以嚣嚣矣。故士穷不失义,达不离道。穷不失义,故士得己焉;达不离道,故民不失望焉。古之人,得志,...
    Sunny飞镜阅读 162评论 0 0
  • 文/亭玉子 请允许我为了心中的爱奋不顾身一次, 就这一次就足矣。 我那么拼命那么努力, 只为了亲口对他说那句:我爱...
    亭玉子阅读 588评论 3 7