java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Spring切面优先级

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

作者:学习使我快乐T

这篇文章主要介绍了Spring切面的优先级与基于xml的AOP的详细步骤,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

一、切面的优先级

①创建类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);
    }
}

到此这篇关于Spring切面优先级与基于xml的AOP实现方法详解的文章就介绍到这了,更多相关Spring切面优先级内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文