Spring切面优先级与基于xml的AOP实现方法详解

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Spring切面优先级与基于xml的AOP实现方法详解

学习使我快乐T   2022-11-10 我要评论

一、切面的优先级

①创建类ValidateAspect:

由于要把我们的切面类和我们的目标类来进行ioc容器的一个组件,所以我们需要加上@Component注解,然后由于我们要把当前切面类来标识为一个组件,我们需要@Aspect注解

切面的优先级:

可以通过@Order注解的value属性设置优先级,默认值为Integer的最大值

@Order注解的value属性值越小,优先级越高

@Component
@Aspect
@Order(1)
public class ValidateAspect {
//    @Before("execution(* com.tian.spring.aop.annotation.CalculatorImpl.*(..))")
    @Before("com.tian.spring.aop.annotation.LoggerAspect.pointCut()")
    public void beforeMethod() {
        System.out.println("ValidateAspect-->前置通知");
    }
}

②测试类:

public class AOPTest {
    @Test
    public void testAOPByAnnotation() {
        ApplicationContext ioc = new ClassPathXmlApplicationContext("aop-annotation.xml");
        Calculator calculator = ioc.getBean(Calculator.class);
        calculator.div(10,1);
    }
}

二、基于xml的AOP实现(了解)

①复制基于注解的AOP实现的四个接口和类

②删除@Aspect注解(将组件标识为切面),切入点表达式的注解@Pointcut,把方法标识为通知方法的注解@Before...,@Order注解

③创建xml文件

    <!--扫描组件-->
    <context:component-scan base-package="com.tian.spring.aop.xml"></context:component-scan>
    <aop:config>
        <!--设置一个公共的切入点表达式-->
        <aop:pointcut id="pointCut" expression="execution(* com.tian.spring.aop.xml.CalculatorImpl.*(..))"/>
        <!--将IOC容器中的某个bean设置为切面-->
        <aop:aspect ref="loggerAspect">
            <aop:before method="beforeAdviceMethod" pointcut-ref="pointCut"></aop:before>
            <aop:after method="afterAdviceMethod" pointcut-ref="pointCut"></aop:after>
            <aop:after-returning method="afterReturningAdviceMethod" returning="result" pointcut-ref="pointCut"></aop:after-returning>
            <aop:after-throwing method="afterThrowingAdvice" throwing="ex" pointcut-ref="pointCut"></aop:after-throwing>
            <aop:around method="aroundAdviceMethode" pointcut-ref="pointCut"></aop:around>
        </aop:aspect>
        <aop:aspect ref="validateAspect" order="1">
            <aop:before method="beforeMethod" pointcut-ref="pointCut"></aop:before>
        </aop:aspect>
    </aop:config>

④测试类:

public class AOPByXMLTest {
    @Test
    public void testAOPByXML() {
        ApplicationContext ioc = new ClassPathXmlApplicationContext("aop-xml.xml");
        Calculator calculator = ioc.getBean(Calculator.class);
        calculator.add(1,2);
    }
}

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们