aop-基于注解的aspectJ

1、class MyAspect

package com.annotation;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class MyAspect {

@Before("execution(* *..ISomeService.doFirst(..))")
public void myBefore() {
	System.out.println("执行前置通知方法");
}

@Before("execution(* *..ISomeService.doFirst(..))")
public void myBefore(JoinPoint jp) {
	System.out.println("执行前置通知方法 jp = " + jp);
}

@AfterReturning(value = "execution(* *..ISomeService.doSecond(..))", returning = "result")
public void myAfterReturning(Object result) {
	System.out.println("执行后置通知方法 result = " + result);
}

@Around(value = "execution(* *..ISomeService.doSecond(..))")
public Object myAround(ProceedingJoinPoint pjp) throws Throwable {
	System.out.println("执行环绕通知方法, 目标方法执行之前");
	Object result = pjp.proceed();
	System.out.println(result);
	System.out.println("执行环绕通知方法, 目标方法执行之后");
	return result;
}

@AfterThrowing(value = "doThirdPointCut()",throwing = "ex")
public void myAfterThrowing(Exception ex) {
	System.out.println("执行异常通知方法 ex = " + ex.getMessage());
}

//定义一个切入点,名字叫doThirdPointCut()
@Pointcut(value = "execution(* *..ISomeService.doThird(..))")
public void doThirdPointCut() {}

@After(value = "doThirdPointCut()")
public void myAfter() {
	System.out.println("执行最终通知方法 ");
}

}

2、class MyTest

package com.annotation;

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

public class MyTest {

public static void main(String[] args) {
	
	ApplicationContext ac = new ClassPathXmlApplicationContext("com/annotation/applicationContext.xml");
	ISomeService service = (ISomeService) ac.getBean("mySomeService");
	
	service.doFirst();
	System.out.println("----------------------------------");
	service.doSecond();
	System.out.println("----------------------------------");
	service.doThird();
}

}

3、applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>

<bean id="mySomeService" class="com.annotation.SomeServiceImpl"/>

<bean id="myAspect" class="com.annotation.MyAspect"/>

<aop:aspectj-autoproxy/>
发布了46 篇原创文章 · 获赞 1 · 访问量 383

猜你喜欢

转载自blog.csdn.net/weixin_43925059/article/details/105054604