【深入Spring】Spring使用AOP的几种方式

1.经典的基于代理的AOP

[1]前置通知

public class BeforeAdvice implements MethodBeforeAdvice{

    @Override
    public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable {
        System.out.println("前置通知");
        /*
         * arg0 切点的方法
         * arg1 切点的方法形参
         * arg3 切点所在的对象
        */
    }
    
}

[2]后置通知

public class AfterAdvice implements AfterReturningAdvice{

    @Override
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("后置通知");
    }

}

[3]环绕通知

public class AroundAdvice implements MethodInterceptor{

    @Override
    public Object invoke(MethodInvocation arg0) throws Throwable {
        System.out.println("环绕通知前");
        Object proceed = arg0.proceed();
        System.out.println("环绕通知后");
        return proceed;
    }

}

[4]异常通知

public class ExceptionAdvice implements ThrowsAdvice{
    public void afterThrowing(Exception ex){
        System.err.println(ex.getMessage());
        System.out.println("异常通知");
    }
}

[5]application.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"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!-- 注册代理目标类 -->
    <bean id="someServiceImpl" class="com.bjsxt.service.SomeServiceImpl"></bean>
    
    <!-- 注册前置通知 -->
    <bean id="beforeAdvice" class="com.bjsxt.advice.BeforeAdvice"></bean>
    
    <!-- 注册后置通知 -->
    <bean id="afterAdvice" class="com.bjsxt.advice.AfterAdvice"></bean>
    
    <!-- 注册环绕通知 -->
    <bean id="aroundAdvice" class="com.bjsxt.advice.AroundAdvice"></bean>
    
    <!-- 注入异常通知 -->
    <bean id="exceptionAdvice" class="com.bjsxt.advice.ExceptionAdvice"></bean>
    
    <!-- 注册代理工厂Bean --> 
    <bean id="proxyFactoryBean" class="org.springframework.aop.framework.ProxyFactoryBean">
        <!-- 配置目标类-->
        <property name="targetName" value="someServiceImpl"></property>
        
        <!-- 配置拦截时执行的通知 -->
        <property name="interceptorNames">
            <!-- 字符串数组 -->
            <!-- 方式一   在property标签中的value属性中用,分隔注入  例如:(value="beforeAdvice,afterAdvice")-->
            <!-- 方式二 (数组注入)-->
            <array>
                <value>beforeAdvice</value>
                <value>afterAdvice</value>
                <value>aroundAdvice</value>
                <value>exceptionAdvice</value>
            </array>
        </property>
        
        <!-- 配置目标类的接口 -->
        <property name="interfaces">
            <list>
                <!-- (字节码对象数组)注意:字节码对象可以直接在value属性中表示 -->
                <value>com.bjsxt.service.SomeService</value>
            </list>
        </property>
    </bean>
   
</beans>
QQ截图20190214203643.png
2.通过AspectJ提供的注解实现AOP

AspectJ对AOP的实现
对于AOP这种编程思想,很多框架都进行了实现。Spring就是其中之一,可以完成面向切面编程。然而,AspectJ也实现了AOP的功能,且其实现方式更为简捷,使用更为方便,而且还支持注解式开发。所以,Spring又将AspectJ的对于AOP的实现也引入到了自己的框架中。
在Spring中使用AOP开发时,一般使用AspectJ的实现方式。

AspectJ中常用的通知有五种类型:

           前置通知 
           后置通知 
           环绕通知 
           异常通知 
           最终通知:无论程序执行是否正常,该通知都会执行。类似于try..catch中finally代码块。 

AspectJ的切入点表达式 (execution)
举例:
execution(public * (..))
指定切入点为:任意公共方法。
execution(
set (..))
指定切入点为:任何一个以"set"开始的方法。
execution(
com.xyz.service..(..))
指定切入点为:定义在service包里的任意类的任意方法。
execution(* com.xyz.service...(..))
指定切入点为:定义在service包或者子包里的任意类的任意方法。".."出现在类名中时,后面必须跟"",表示包、子包下的所有类。
execution(
.service..(..))
指定只有一级包下的serivce子包下所有类(接口)中的所有方法为切入点
execution(
..service..*(..))
指定所有包下的serivce子包下所有类(接口)中的所有方法为切入点

untitled.png

切入点表达式要匹配的对象就是目标方法的方法名。所以,execution表达式中明显就是方法的签名。注意,表达式中加[ ]的部分表示可省略部分,各部分间用空格分开。在其中可以使用以下符号

untitled2.png

代码示例

@Component("myAspect")
@Aspect  //表明当前类是一个切面 
public class MyAspect {
    @Before(value="execution(* *..service.*.*(..))")
    public void before(JoinPoint joinPoint) throws Throwable {
        System.out.println("前置通知"+jp);
                //通过JoinPoint 获取切点方法的参数列表集合
               Object[] args = joinPoint.getArgs();
                //获取切点所在的目标对象
                Object target = joinPoint.getTarget();
                //获取切点的方法的对象
            Signature signature = joinPoint.getSignature();
        MethodSignature ms = (MethodSignature)signature;
        Method method = ms.getMethod();
    }
    @Around(value="execution(* *..service.*.*(..))")
    public Object around(ProceedingJoinPoint arg0) throws Throwable {
        System.out.println("环绕通知前");
        Object proceed = arg0.proceed();
        
        if(proceed!=null){
            System.out.println(proceed.toString().toUpperCase());
        }
        System.out.println("环绕通知后");
        return proceed;
    }
    
    @AfterReturning(value="execution(* *..service.*.*(..))",returning="result")
    public void afterReturning(Object result) throws Throwable {
        System.out.println("后置通知");
        System.out.println("后置通知获取返回值:"+result);
    }
    
    @AfterThrowing(value="execution(* *..service.*.*(..))" ,throwing="ex")
    public void afterThrowing(Exception ex){
        System.out.println("异常通知"+ex.getMessage());
    }
    
    //使用@After(value="pointcut()"),表示继承了方法pointcut()的切入表达式:execution(* *..service.*.*(..))。
    @After(value="pointcut()")
    public void after(){
        System.out.println("最终通知");
    }
    @Pointcut("execution(* *..service.*.*(..))")
    public void pointcut(){
        
    }
    
}

application.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.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">

    
   
    <context:component-scan base-package="com.terence.aop.aspectj"/>
    <!-- 配置切面自动代理 -->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
    
   
</beans>
3.AspectJ通过XML方式实现AOP
        <!-- 注册目标类 --> 
       <bean id="someServiceImpl" class="com.bjsxt.service.impl.SomeServiceImpl"></bean> 
       <!-- 注册切面--> 
       <bean id="myAspect" class="com.bjsxt.aspects.MyAspect"></bean> 
        
       <!-- aop配置 --> 
       <aop:config> 
               <!-- 指定切入点 --> 
               <aop:pointcut expression="execution(* *..service.*.doSome(..))" id="doSomePC"/> 
               <aop:pointcut expression="execution(* *..service.*.doOther(..))" id="doOtherPC"/> 
               <!-- 指定切面 --> 
               <aop:aspect ref="myAspect"> 
                       <!-- 指定切面当中的前置通知方法 --> 
                     
                       <aop:before method="before" pointcut-ref="doSomePC"/> 
                       <aop:before method="before(org.aspectj.lang.JoinPoint)" pointcut-ref="doSomePC"/> 
                         
                       <!-- 指定切面当中的后置通知方法 --> 
                       <aop:after-returning method="afterReturning(java.lang.Object)" pointcut-ref="doOtherPC" returning="result"/> 

                       <!-- 指定切面当中的环绕通知方法 --> 
                       <aop:around method="around" pointcut-ref="doOtherPC"/> 

                       <!-- 指定切面当中的异常通知方法 --> 
                       <aop:after-throwing method="afterThrowing(java.lang.Exception)" pointcut-ref="doSomePC" throwing="ex"/> 

                       <!-- 指定切面当中的最终通知方法 --> 
                       <aop:after method="after" pointcut-ref="doSomePC"/> 
               </aop:aspect> 
       </aop:config> 

4.基于Scheme-base的AOP
<?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:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!-- 注册user实体类 -->
    <bean id="user" class="com.bjsxt.pojo.User"></bean>
    
    <!-- 注册前置通知 -->
    <bean id="before" class="com.bjsxt.advice.BeforeAdvice"></bean>
    
    <!-- 注册后置通知 -->
    <bean id="after" class="com.bjsxt.advice.AfterAdvice"></bean>
    
    <!-- 注册环绕通知 -->
    <bean id="run" class="com.bjsxt.advice.RunAdvice"></bean>
    
    <!-- 注册异常通知 -->
    <bean id="exception" class="com.bjsxt.advice.ExceptionAdvice"></bean>
    <!-- 配置aop -->
    <aop:config>
        <!-- 选择切点 -->
        <!-- 指定方法的切点 -->
        <aop:pointcut expression="execution(* com.bjsxt.pojo.User.b(String))" id="point"/>
        <!-- ..代表有参数和无参数都行 -->
        <aop:pointcut expression="execution(* com.bjsxt.pojo.User.b(..))" id="point2"/>
        <!-- *代表通配符 (User类的所有方法都是切点) -->
        <aop:pointcut expression="execution(* com.bjsxt.pojo.User.*(..))" id="point3"/>
        <!-- pojo报下的所有方法都是切点 -->
        <aop:pointcut expression="execution(* com.bjsxt.pojo.*.*(..))" id="point4"/>
        <!-- 定义切面 -->
        <aop:advisor advice-ref="before" pointcut-ref="point"/>
        <aop:advisor advice-ref="after" pointcut-ref="point"/>
        <aop:advisor advice-ref="run" pointcut-ref="point"/>
        <aop:advisor advice-ref="exception" pointcut-ref="point"/>
    </aop:config>
</beans>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,290评论 4 363
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,399评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,021评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,034评论 0 207
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,412评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,651评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,902评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,605评论 0 199
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,339评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,586评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,076评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,400评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,060评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,083评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,851评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,685评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,595评论 2 270

推荐阅读更多精彩内容

  • IoC 容器 Bean 的作用域 自定义作用域实现 org.springframework.beans.facto...
    Hsinwong阅读 2,410评论 0 7
  • AOP实现可分为两类(按AOP框架修改源代码的时机): 静态AOP实现:AOP框架在编译阶段对程序进行修改,即实现...
    数独题阅读 2,253评论 0 22
  • 概述 Spring是什么? Spring是一个开源框架,为了解决企业应用开发的复杂性而创建的,但是现在已经不止于企...
    琅筑阅读 1,110评论 2 8
  • 一、AOP 简介 AOP(Aspect-Oriented Programming, 面向切面编程): 是一种新的方...
    leeqico阅读 747评论 0 1
  • Spring的AOPAOP的基本概念基于注解的“零配置”方式定义切面Bean定义Before增强处理定义After...
    渐丶忘阅读 1,559评论 0 0