1 @Aspect // 表示当前类切面
2 public class MyAspect {
3
4 @Before("execution(* *..ISomeService.doFirst(..))")
5 public void before(JoinPoint jp) {
6 System.out.println("执行 before2" + jp);
7 }
8
9 @AfterReturning(value = "execution(* *..ISomeService.doSecond(..))", returning = "result")
10 public void myAfterReturning(Object result) {
11 System.out.println("执行 my after, result" + result);
12 }
13
14 // 定义了一个切入点
15 @Pointcut("execution(* *..ISomeService.doThird(..))")
16 public void doThirdPointCut(){}
17
18 @Around("doThirdPointCut()")
19 public Object myAround(ProceedingJoinPoint pp) throws Throwable {
20 System.out.println("执行around1");
21 Object res = pp.proceed();
22 System.out.println("执行around2 " + res);
23 return res;
24 }
25
26 }
1 <bean id="myAspect" class="day1208.MyAspectXML"/>
2 <bean id="someService" class="day1208.ServiceImpl"/>
3 <aop:aspectj-autoproxy/>
如果运行的时候出现error at ::0 can't find referenced pointcut, 一般是因为jdk版本和AspectJ.Weaver不一致.
1.6以下的aspectj需要用jdk1.6运行.
1 public class MyAspectXML {
2
3 public void before(JoinPoint jp) {
4 System.out.println("执行 before2" + jp);
5 }
6
7 public void myAfterReturning(Object result) {
8 System.out.println("执行 my after, result" + result);
9 }
10 public void myAfterReturning() {
11 System.out.println("执行 my after, no result");
12 }
13
14 public void doThirdPointCut(){}
15
16 public Object myAround(ProceedingJoinPoint pp) throws Throwable {
17 System.out.println("执行around1");
18 Object res = pp.proceed();
19 System.out.println("执行around2 " + res);
20 return res;
21 }
22
23 }
1 <aop:config>
2 <aop:pointcut id="secondPT" expression="execution(* *..ISomeService.doSecond(..))"/>
3 <aop:aspect ref="myAspect">
4 <aop:before method="before" pointcut="execution(* *..ISomeService.doFirst(..))"/>
5 <aop:after-returning method="myAfterReturning(java.lang.Object)" pointcut-ref="secondPT" returning="result"/>
6 </aop:aspect>
7 </aop:config>