Spring Aop 注解

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"/>

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值