package com.spring.aop.test;
public class My {
public String testAop() throws Exception {
System.out.println("test aop");
int i = 10;
if (i > 1) {
//throw new Exception("i > 1");
}
return "aop is ok";
}
}
package com.spring.aop.test;
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.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
@Aspect
public class MyAspect {
/**
* 调用前通知
*/
@Before(value="execution(* com.spring.aop.test.*.*(..))")
public void before(JoinPoint jp){
System.out.println("aspect - befoer " + jp.toString());
}
/**
* 抛出异常后通知
*/
@AfterThrowing(value="execution(* com.spring.aop.test.*.*(..))", throwing="ex")
public void afterThrowing(Exception ex) {
System.out.println("aspect - after throwing " + ex.getMessage());
}
/**
* 环绕通知
*/
@Around(value="execution(* com.spring.aop.test.*.*(..))")
public Object around(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("aspect - around before");
Object result = pjp.proceed();
System.out.println("aspect - around after");
return result;
}
/**
* 调用后通知
*/
@After(value="execution(* com.spring.aop.test.*.*(..))")
public void after(JoinPoint jp) {
System.out.println("aspect - after " + jp.toString());
}
/**
* 调用返回后通知
*/
@AfterReturning(value="execution(* com.spring.aop.test.*.*(..))")
public void afterReturn(JoinPoint jp) {
System.out.println("aspect - after returning " + jp.toShortString());
}
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"applicationContext.xml"});
My my = (My)context.getBean("my");
try {
String s = my.testAop();
System.out.println(s);
} catch (Exception e) {
System.out.println("最外层捕获异常:" + e.getMessage());
}
}
}
<bean id="my" class="com.spring.aop.test.My"></bean>
<bean id="myAspect" class="com.spring.aop.test.MyAspect"></bean>
<!-- 使用CGLIB代理和@AspectJ自动代理支持-->
<aop:aspectj-autoproxy proxy-target-class="true"/>
本文通过具体示例展示了 Spring AOP 的应用,包括前置、后置、环绕等通知类型,并结合异常处理说明了如何增强应用程序的功能。
3632

被折叠的 条评论
为什么被折叠?



