转载自:http://blog.csdn.net/yl_wh/article/details/8473510
- 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"/>