AspectJ的注解开发AOP:后置通知的学习

后置通知使用 @AfterReturing 

它可以获取我们方法的返回值

通过returning属性可以定义方法返回值,作为参数

后置通知基本使用方式如下:

在ApplicationContex.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">
        <!--开启aspectJ的注解开发,AspectJ的自动代理-->
        <aop:aspectj-autoproxy/>


        <!--目标类-->
        <bean id="xiaomao" class="com.AspecJ.xiaomaoDao"></bean>

        <!--切面类-->
        <bean class="com.AspecJ.aspectj"/>


</beans>

在目标类中有如下的方法:

package com.AspecJ;

public class xiaomaoDao {
    public void save(){
        System.out.println("save xiaomao!");
    }
    public void find(){
        System.out.println("find xiaomao!");
    }
    public String delete(){
        System.out.println("delete xiaomao!");
        return "xiaomao";
    }
    public void update(){
        System.out.println("update xiaomao!");
    }
}

在切面类中定义如下:

package com.AspecJ;


import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class aspectj {
//    @Before(value = "execution(* com.AspecJ.xiaomaoDao.*(..))")
//    public void before(){
//        System.out.println("我是前置通知!");
//    }


    @AfterReturning(value = "execution(* com.AspecJ.xiaomaoDao.delete())",returning = "element")
//    使用returning来接受返回值
    public void After(Object element){
        System.out.println("我删除了"+element); //打印输出了返回值
    }
}

最后的返回值如下

我是前置通知!
delete xiaomao!
我删除了xiaomao
我是前置通知!
find xiaomao!
我是前置通知!
save xiaomao!
我是前置通知!
update xiaomao!

猜你喜欢

转载自www.cnblogs.com/xiaolaha/p/11368643.html