spring AOP

springAOP面向切面的简单应用

需要两个类,一个类作为切入点,一个类作为切面类。

两种方法:编写XML配置文件和使用注解
1.使用编写XML文件的方式:

切入点类

public class Test {

	public void ts() {
		System.out.println("一个普通方法");
		throw new NullPointerException();
	}

}

切面类

public class AopQ {

	public void beFore(){
		System.out.println("前置通知");
	}
	
	public void after(){
		System.out.println("后置通知");
	}
	
	public void returning(Object ar){
		System.out.println("返回后通知"+ar.toString());
	}
	
	public void thorwing(NullPointerException e){
		System.out.println("抛出异常后通知"+e.toString());
	}
	
}

配置文件

	<aop:config>
	
		<aop:aspect id="asp" ref="aq"><!-- bean id为aq的类作为切面类 -->
			<aop:pointcut expression="excution(* com.anzhuo.jiangyiling.Test.*(..))" id="poi"/><!-- 规定切入点,切入规则 -->
			<aop:before pointcut-ref="poi" method="beFore"/>
			<aop:after pointcut-ref="poi" method="after"/>
			<aop:after-returning pointcut-ref="poi" method="retruning" returning="ar"/>
			<aop:after-throwing pointcut-ref="poi" method="throwing" throwing="e"/>
		</aop:aspect>
	
	</aop:config>
2.使用注解的方式:

在切面类中

@Aspect//此类作为切面类
public class AopQ {
	
	@Pointcut("execution(* com.anzhuo.jiangyiling.*.*(..))")//规定切入点,切入规则
	public void qr(){}

	@Before("qr()")
	public void beforeA(){
		System.out.println("前置");
	}
	
	@AfterReturning(pointcut="qr()",returning="s")
	public void afterR(String s){
		System.out.println("返回后通知");
	}
	
	@AfterThrowing(pointcut="qr()",throwing="o")
	public void afterT(Object o){
		System.out.println("抛出异常后通知");
	}
	
}

配置文件中只需加上<aop:aspectj-autoproxy/>

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值