Spring4---AOP切面详解

切面的优先级

在这里插入图片描述

  • 示例:
  • 现在有四个java程序,
    1. CalcUtil:一个接口,定义了加减乘除的抽象方法
    2. IntCalc:接口的一个子类实现,实现了整形的方法实习
    3. LogAspect:一个AOP切面,负责在IntCalc类中执行任何方法时打印日志
    4. ValidateAspect:另一个AOP切面负责在IntCalc类中执行任何方法是印证参数是否为正数
  • 此时IntCalc类中的方法同时应用了两处切面,要使ValidateAspect切面先执行
@Aspect
@Component
@Order(0)   //使用@Order标签定义切面的优先级
            //数字越小越先执行
public class ValidateAspect {
    @Before("execution(* mao.shu.spring.aop.aspectJ.*(..))")
    public void validate(JoinPoint joinPoint){
        Object[] args = joinPoint.getArgs();
        for (Object a : args){
            Integer temp = new Integer(String.valueOf(a));
            if(temp < 0 ){
                System.out.println( a + " 参数小于 0 请输入正整数");
            }
        }
    }
}

  • 定义LogAspect的优先级
@Aspect//声明这个Bean是一个切面
@Component//声明该类是一个IOC容器中的Bean
@Order(1)
public class LogAspect {
  • 测试
package mao.shu.spring.aop.aspectJ;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import static org.junit.Assert.*;

public class IntCalcTest {
    @Test
    public void test() throws Exception {
        ApplicationContext app = new ClassPathXmlApplicationContext("mao/shu/spring/aop/aspectJ/aspectJ.xml");
        IntCalc intCalc = (IntCalc) app.getBean("intCalc");

        System.out.println(intCalc.plus(-100, 678));
    }
}

在这里插入图片描述

重用切入点定义

在这里插入图片描述

在这里插入图片描述

  • 示例:单独写一个类用于定义公共的切入点表达式
  • PointcutUtil
public class PointcutUtil {
    @Pointcut("execution(* mao.shu.spring.aop.aspectJ.IntCalc.*(..))")
    public void pointcut(){}
}
  • 在其他切面中使用这个公共的切入点
@Before("PointcutUtil.pointcut()")//引用重用的切入点表达式
                                    // 因为在同一个包下,所以可以使用 "类名称.方法名"引用
public void validate(JoinPoint joinPoint){
    Object[] args = joinPoint.getArgs();
    for (Object a : args){
        Integer temp = new Integer(String.valueOf(a));
        if(temp < 0 ){
            System.out.println( a + " 参数小于 0 请输入正整数");
        }
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值