Spring-AOP-通知方法(增强方法)获取目标方法详细信息(JoinPoint joinPoint)

Spring-AOP-通知方法(增强方法)获取目标方法详细信息

(1)只需要为通知方法的参数列表写上一个参数JoinPoint joinPoint

  JoinPoint joinPoint:封装了当前目标方法的详细信息

    getArgs():获取目标方法运行时使用的参数

    getSignature():获取方法签名

    getSignature().getName():获取方法名

  注解里使用returning属性告诉Spring哪个参数接受返回值

  注解里使用throwing属性告诉Spring哪个参数接受异常

 

@Service
public class UserService {

    public int add(int i,int j)
    {
        System.out.println("UserService add...");
        //System.out.println(1/0);
        return i+j;
    }
}

 

@Component
@Aspect
public class UserServiceProxy {

    @After(value = "execution( * com.orz.spring.aop.UserService.add(..))")
    public void logAfter(JoinPoint joinPoint)
    {
        System.out.println("@After----["+joinPoint.getSignature().getName()+"]方法调用了");
    }



    @Before(value = "execution( * com.orz.spring.aop.UserService.add(..))")
    public void logBefore(JoinPoint joinPoint)
    {
        System.out.println("@Before----["+joinPoint.getSignature().getName()+"]方法调用了,参数为【"+ Arrays.asList(joinPoint.getArgs())+"】");

    }

    @AfterReturning(value = "execution(* com.orz.spring.aop.UserService.add(..))",returning = "result")
    public void logAfterReturning(JoinPoint joinPoint,Object result)
    {
        System.out.println("@AfterReturning----["+joinPoint.getSignature().getName()+"]方法调用了,结果为【"+result+"】");

    }


    @AfterThrowing(value = "execution( * com.orz.spring.aop.UserService.add(..))",throwing = "exception")
    public void logAfterThrowing(JoinPoint joinPoint,Exception exception)
    {
        System.out.println("@AfterThrowing----["+joinPoint.getSignature().getName()+"]方法调用了,异常信息为【"+exception+"】");
        System.out.println("@AfterThrowing");
    }

}

 

@Test
public void test1()
{
    ApplicationContext applicationContext=new ClassPathXmlApplicationContext("bean.xml");
    UserService userService = applicationContext.getBean("userService", UserService.class);
    userService.add(1,2);
}
View Code
@Before----[add]方法调用了,参数为【[1, 2]】

UserService add...

@AfterReturning----[add]方法调用了,结果为【3】

@After----[add]方法调用了
View Code
public class UserService {

    public int add(int i,int j)
    {
        System.out.println("UserService add...");
        System.out.println(1/0);
        return i+j;
    }
}
View Code
@Before----[add]方法调用了,参数为【[1, 2]】

UserService add...

@AfterThrowing----[add]方法调用了,异常信息为【java.lang.ArithmeticException: / by zero】

@AfterThrowing

@After----[add]方法调用了
View Code

 

posted @ 2020-10-24 16:47  orz江小鱼  阅读(458)  评论(0编辑  收藏  举报