设为首页 加入收藏

TOP

12、Spring之基于xml的AOP(四)
2023-08-26 21:10:55 】 浏览:83
Tags:Spring xml AOP
gerAspect-->环绕返回通知,方法名:"+methodName+",结果:"+ result); } catch (Throwable throwable) { throwable.printStackTrace(); System.out.println("LoggerAspect-->环绕异常通知,方法名:"+methodName+",异常:"+ throwable); }finally { System.out.println("LoggerAspect-->环绕后置通知,方法名:"+methodName+",参数:"+ Arrays.toString(args)); } return result; }

12.5.2、配置环绕通知到切面

image

            <!--
                aop:around标签:将方法设置为该切面的环绕通知(方法),效果等同于@Around注解
            -->
            <aop:around method="aroundMethod" pointcut-ref="pointcutOne"></aop:around>

12.5.3、测试使用效果

image

注意:因为环绕通知包括了其他四种通知,所以一般要么配置其他四种通知,要么只配置环绕通知;
本示例为了展示效果才同时配置

    @Test
    public void testAOPByXML(){
        ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-aopByxml.xml");

        // 虽然不知道代理对象的类名,但可以通过代理对象和目标对象共同实现的接口类型来从ioc容器中获取代理对象
        Calculator calculator = ioc.getBean(Calculator.class);

        // 只能通过代理对象来访问目标对象中的方法
        calculator.div(1,1);

    }

12.6、切面的优先级

12.6.1、创建其他切面类ValidateAspect

image

package org.rain.spring.aop.xml;

import org.springframework.stereotype.Component;

/**
 * @author liaojy
 * @date 2023/8/20 - 23:59
 */
// @Component注解:保证这个目标类能够放入IOC容器
@Component
public class ValidateAspect {
}

12.6.2、定义前置通知的功能

image

    public void beforeMethod(){
        System.out.println("ValidateAspect-->前置通知");
    }

12.6.3、配置前置通知到切面

image

        <aop:aspect ref="validateAspect">
            <aop:before method="beforeMethod" pointcut-ref="pointcutOne"></aop:before>
        </aop:aspect>

12.6.4、测试使用效果

image

由控制台日志可知,ValidateAspect切面的前置通知方法生效了,但执行顺序在LoggerAspect切面的前置通知方法的后面

    @Test
    public void testAOPByXML(){
        ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-aopByxml.xml");

        // 虽然不知道代理对象的类名,但可以通过代理对象和目标对象共同实现的接口类型来从ioc容器中获取代理对象
        Calculator calculator = ioc.getBean(Calculator.class);

        // 只能通过代理对象来访问目标对象中的方法
        calculator.div(1,1);

    }

12.6.5、调整切面的优先级

image

        <!--
           aop:aspect标签的order属性:用于设置切面的优先级,value属性值越小,优先级越高,默认值为Integer的最大值
        -->
        <aop:aspect ref="validateAspect" order="2023">
            <aop:before method="beforeMethod" pointcut-ref="pointcutOne"></aop:before>
        </aop:aspect>

12.6.6、测试调整后的效果

image

由控制台日志可知,ValidateAspect切面的前置通知方法的执行顺序,在LoggerAspect切面的前置通知方法的前面

这是因为ValidateAspect切面的Order属性值已设为2023,要小于LoggerAspect切面所使用的默认值(Integer的最大值2147483647)

首页 上一页 1 2 3 4 下一页 尾页 4/4/4
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Docker下elasticsearch8部署、扩.. 下一篇面试官:String.intern() 有什么..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目