spring-aop的五种通知方式

微微亮      2022-05-20     149

关键词:

AOP的五种通知方式:

前置通知:在我们执行目标方法之前运行(@Before

后置通知:在我们目标方法运行结束之后,不管有没有异常(@After

返回通知:在我们的目标方法正常返回值后运行(@AfterReturning

异常通知:在我们的目标方法出现异常后运行(@AfterThrowing

环绕通知:目标方法的调用由环绕通知决定,即你可以决定是否调用目标方法,joinPoint.procced()就是执行目标方法的代码 。环绕通知可以控制返回对象(@Around)

一、导jar包

com.springsource.net.sf.cglib-2.2.0.jar
com.springsource.org.aopalliance-1.0.0.jar
com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
commons-logging-1.1.3.jar
spring-aop-4.0.0.RELEASE.jar
spring-aspects-4.0.0.RELEASE.jar
spring-beans-4.0.0.RELEASE.jar
spring-context-4.0.0.RELEASE.jar
spring-core-4.0.0.RELEASE.jar
spring-expression-4.0.0.RELEASE.jar
spring-jdbc-4.0.0.RELEASE.jar
spring-orm-4.0.0.RELEASE.jar
spring-tx-4.0.0.RELEASE.jar
spring-web-4.0.0.RELEASE.jar
spring-webmvc-4.0.0.RELEASE.jar

二、在类路径下建applicationContext.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:context="http://www.springframework.org/schema/context"

       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
                            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    <!--配置自动扫描的包-->
    <context:component-scan base-package="com.atguigu.spring.aop"></context:component-scan>

    <!--配置自动为匹配aspectJ 注解的Java类生成代理对象-->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

</beans>

三、接口

//接口
public interface ArithmeticCalculator {

    int add(int i, int j);

    int sub(int i, int j);

    int mul(int i, int j);

    int div(int i, int j);
}

四、实现类

package com.atguigu.spring.aop;

import org.springframework.stereotype.Component;

/**
 * @Author 谢军帅
 * @Date2019/12/6 21:23
 * @Description
 */

//实现类
@Component("arithmeticCalculator")
public class ArithmeticCalculatorImpl implements ArithmeticCalculator {
    @Override
    public int add(int i, int j) {
        int relust = i+j;
        return relust;
    }

    @Override
    public int sub(int i, int j) {
        int relust = i-j;
        return relust;
    }

    @Override
    public int mul(int i, int j) {
        int relust = i*j;
        return relust;
    }

    @Override
    public int div(int i, int j) {
        int relust = i/j;
        return relust;
    }
}

五、定义切面类

package com.atguigu.spring.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * @Author 谢军帅
 * @Date2019/12/11 11:17
 * @Description
 */
@Component
@Aspect
public class LoggingAspect {
    /**
     * 在每一个接口的实现类的每一个方法开始之前执行一段代码
     */

    @Before("execution(public int com.atguigu.spring.aop.ArithmeticCalculator.* (..))")
    public void beforeMethod(JoinPoint joinPoint){
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();

        System.out.println("The method "+methodName+" begins with "+ Arrays.asList(args));
    }

    @After("execution(public int com.atguigu.spring.aop.ArithmeticCalculator.* (..))")
    public void afterMethod(JoinPoint joinPoint){
        String methodName = joinPoint.getSignature().getName();

        System.out.println("The method "+methodName +" end......");
    }


    /**
     * 返回通知
     * 在方法正常结束后执行的代码
     * 返回通知是可以访问方法的返回值的!
     * @param joinPoint*/
     
    @AfterReturning(value = "execution(public int com.atguigu.spring.aop.ArithmeticCalculator.* (..))",
                    returning = "result")
    public void afterReturning(JoinPoint joinPoint,Object result){
        String methodName = joinPoint.getSignature().getName();
        System.out.println("The method "+methodName +" end......result:"+result);
    }


    /**
     * 在目标方法出现异常时会执行的代码
     * 可以访问到异常对象,且可以指定在出现特定异常时在执行通知代码
     * @param joinPoint
     * @param ex*/
     
    @AfterThrowing(value = "execution(public int com.atguigu.spring.aop.ArithmeticCalculator.* (..))", throwing = "ex")
    public void afterThrowing(JoinPoint joinPoint, Exception ex){
        String methodName = joinPoint.getSignature().getName();
        System.out.println("The method "+methodName +"occurs exception :" +ex);
    }

    /**
     * 环绕通知需要携带 ProceedingJoinPoint 类型的参数
     * 环绕通知类似于动态代理的全过程:ProceedingJoinPoint 类型的参数可以决定是否执行目标方法。
     * 且环绕通知必须有返回值,返回值即为目标方法的返回值
     * @param proceedingJoinPoint
     */
    /*@Around("execution(public int com.atguigu.spring.aop.ArithmeticCalculator.* (..))")
    public Object aroundMethod(ProceedingJoinPoint proceedingJoinPoint){

        Object result = null;
        String methodName = proceedingJoinPoint.getSignature().getName();

        try {
            //前置通知
            System.out.println("The method "+methodName+" begins with "+Arrays.asList(proceedingJoinPoint.getArgs()));
            //执行目标方法
            result = proceedingJoinPoint.proceed();

            //返回通知
            System.out.println("The method ends with "+result);
        } catch (Throwable e) {
            //异常通知
            System.out.println("The method occurs exception:"+e);

            throw new RuntimeException(e);
        }

        //后置通知
        System.out.println("The method "+methodName+" ends........");

        return result;
    }*/
}

六、测试

public class Test_aop {

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        ArithmeticCalculator arithmeticCalculator = (ArithmeticCalculator) context.getBean("arithmeticCalculator");

        System.out.println(arithmeticCalculator.getClass().getName());

        int result = arithmeticCalculator.add(1,2);
        System.out.println("result:"+result);

        result = arithmeticCalculator.div(200,0);
        System.out.println("result:"+result);

    }
}

读取属性配置文件的五种方式(代码片段)

读取属性配置文件的五种方式读取属性配置文件的五种方式读取属性配置的示例属性配置文件方式一:使用注解@Value读取属性配置方式二:使用注解@ConfigurationProperties读取属性配置方式三:使用注解@PropertySou... 查看详情

css的五种定位方式

CSS中一共有五种定位: position:static;默认值 position:absolute;绝对定位 position:relative;相对对定位 position:fixed;固定定位 position:sticky;粘性定位其中,粘性定位是CSS3新增加的兼容性比较差定位的作用: 在正常情况下,可... 查看详情

spring-aop的5种通知

SpringAOP五种通知:前置通知,后置通知,返回通知,异常通知,环绕通知首先,配置使用AOP的环境:需要将以下几个包导入到工程中:org.springframework.aop-3.1.1.RELEASE.jar--------spring的面向切面编程,提供AOP(面向切面编程)实现org.s... 查看详情

spring事务配置的五种方式

Spring事务配置的五种方式   前段时间对Spring的事务配置做了比较深入的研究,在此之间对Spring的事务配置虽说也配置过,但是一直没有一个清楚的认识。通过这次的学习发觉Spring的事务配置只要把思路理清,还是比较... 查看详情

ios线程的五种使用方式

//第一种方式  手动创建并启动     NSThread *t = [[NSThread alloc] initWithTarget:self selector:@selector(method) object:nil];     [t start];          //第二种方式  类方法     [NSThread detachNewThreadSelector:@ 查看详情

六:数据存储的五种方式

  iOS开发中数据存在五种存储方式之三:    1.plist(XML属性列表归档)    2.偏好设置    3.NSKeydeArchiver归档(存储自定义对象) 一、plist(XML属性列表归档)只能存取对象类文件第一种方式:(四个文件夹都可... 查看详情

andriod中数据存储的五种方式

数据存储在开发中是使用最频繁的,在这里主要介绍Android平台中实现数据存储的5种方式,分别是:1使用SharedPreferences存储数据2文件存储数据3SQLite数据库存储数据4使用ContentProvider存储数据5网络存储数据 下面将为大家一一详... 查看详情

继承的五种方式

1.混入式继承varobj1={}varobj2={name:‘ys‘,age:18}for(varkinobj2){obj1[k]=obj2[k]}  2.原型继承//方法一:functionPerson(){};varobj1={}varobj2={name:‘ys‘,age:18}obj2=newPersonPerson.prototype=obj2//方法二:funct 查看详情

css清除浮动的五种方式

清除浮动是一件功德无量的事情23333这里记录一下清除浮动的多种方式 *首先要明确的是,为什么要清除浮动?A影响其他元素定位父盒子高度为0,子盒子全部浮动、定位,子盒子不会撑开父盒子,下面的元素会到子盒子的下... 查看详情

button监听点击事件的五种方式

常用方式为匿名类和本类监听的方法。其中本类监听方法需要继承View.OnClickListener接口之后,重写onClick方法。PS:重写某一个方法的快捷键为Ctrl+Opackagecom.example.kimberjin.reviewpro; importandroid.os.Bundle;importandroid.support.annotation.Nullabl... 查看详情

list的五种去重方式(代码片段)

//set集合去重,不改变原有的顺序publicstaticvoidpastLeep1(List<String>list)System.out.println("list=["+list.toString()+"]");List<String>listNew=newArrayList<>();Setset=newHashSet();for(Stringstr: 查看详情

spring管理事务配置的五种方式

spring配置文件中关于事务配置总是由三个组成部分,DataSource、TransactionManager和代理机制这三部分,无论是那种配置方法,一般变化的只是代理机制这块!首先我创建了两个类,一个接口类一个实现类:packagecom.dao;publicinterfaceUserD... 查看详情

圣杯布局的五种方式(代码片段)

方法一center还在文本流之中,会影响到后面的元素,不影响前面的元素<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content= 查看详情

nginxupstream的五种分配方式(代码片段)

Nginx负载均衡选项upstream用法举例1、轮询(weight=1)默认选项,当weight不指定时,各服务器weight相同,每个请求按时间顺序逐一分配到不同的后端服务器,如果后端服务器down掉,能自动剔除。upstreambakendserver192.168.1.10;server192.168.1.11;&... 查看详情

java中创建对象的五种方式

我们总是讨论没有对象就去new一个对象,创建对象的方式在我这里变成了根深蒂固的new方式创建,但是其实创建对象的方式还是有很多种的,不单单有new方式创建对象,还有使用反射机制创建对象,使用clone方法去创建对象,通... 查看详情

物体运动的五种方式(很重要)(代码片段)

1**************************************2物体运动的几种方式:31.4this.transform.position+=Vector3.left*Time.deltaTime;5/*Vector3.left是Vector3的一个属性,表示的是3为坐标系中的向左的单位向量,6实质和newVector3(-1,0,0)是一个效果。还有right,up,down,f 查看详情

字符串拼接的五种方式

参考技术A 虽然字符串是不可变的,但是还是可以通过新建字符串的方式来进行字符串的拼接。常用的字符串拼接方式有五种,分别是使用+、使用concat、使用StringBuilder、使用StringBuffer以及使用StringUtils.join。具体的使用方式... 查看详情

kvm初体验之四:从host登录guest的五种方式

1.virt-viewervirt-viewer-cqemu:///systemvm12.virt-manager(以非root身份运行)virt-manager-cqemu:///system注:若以root身份运行virt-manager会出现“ErrorstartingVirtualMachineManager:Failedtocontactconfigurationserver 查看详情