AOP面向切面编程:AspectJ:xml配置文件开发

String resource = “AspectJapplicationContext.xml”; ApplicationContext applicationContext = new ClassPathXmlApplicationContext(resource); IAspectJService iAspectJService = (IAspectJService) applicationContext.getBean(“aspectJservice”); iAspectJService.doDestroy(); String doFirst = iAspectJService.doFirst(); System.out.println(doFirst);

AspectJapplicationContext.xml配置:
aop:config <aop:pointcut expression=“execution(* …service..*(…))” id=“doExecution”/> <aop:aspect ref=“myAspectJ2”> <aop:before method=“before” pointcut-ref=“doExecution”/> <aop:before method=“before(org.aspectj.lang.JoinPoint)” pointcut-ref=“doExecution”/> <aop:after-returning method=“afterReturning(java.lang.Object)” pointcut-ref=“doExecution” returning=“ret”/> <aop:around method=“around(org.aspectj.lang.ProceedingJoinPoint)” pointcut-ref=“doExecution”/> <aop:after-throwing method=“afterThrowing” pointcut-ref=“doExecution”/> <aop:after-throwing method=“afterThrowing(java.lang.Exception)” pointcut-ref=“doExecution” throwing=“ex”/> <aop:after method=“after” pointcut-ref=“doExecution”/> </aop:aspect> </aop:config>

//定义切入点 @Pointcut("execution(* …service..(…))") public void poin() { } // 前置通知 @Before("execution( …service..(…))") // * …service..(…))"返回所有包含service(字段)包以及其子包以下的方法 public void before() { System.out.println(“AspectJ前置通知”); } // 前置通知,带参数(以下任何通知都能带参数,不一一列举) @Before(“execution(* …IAspectJService.doFirst(…))") // 返回IAspectJService的dofirst方法 public void before(JoinPoint jp) { System.out.println(“AspectJ前置通知:JP=” + jp); } // 后置通知 @AfterReturning(value = “poin()”, returning = “ret”) // 这里 的ret要和下面参数的一致 public void afterReturning(Object ret) { System.out.println(“AspectJ后置通知:返回结果ret=” + ret); System.out.println("----------------------"); } // 环绕通知 @Around(value = "execution( …service..(…))") public Object around(ProceedingJoinPoint pjp) throws Throwable { System.out.println(“AspectJ环绕通知:目标方法执行之前通知”); Object proceed = pjp.proceed(); System.out.println(“AspectJ环绕通知:目标方法执行之后通知”); if (proceed != null) { proceed = ((String) proceed).toUpperCase(); } return proceed; } // 异常通知 @AfterThrowing(value = "execution( …service..(…))") public void afterThrowing() { System.out.println(“AspectJ异常通知”); } // 异常通知:带参数 @AfterThrowing(value = "execution( …service..(…))", throwing = “ex”) public void afterThrowing(Exception ex) { System.out.println(“AspectJ异常通知:ex=” + ex); } // 最终通知 @After("execution( …service.impl..*(…))”) // 返回所有包含service(字段)包的impl实现包以下的方法 public void after() { System.out.println(“AspectJ最终通知”); }

猜你喜欢

转载自blog.csdn.net/weixin_44543131/article/details/113173836
今日推荐