Spring学习笔记二 AOP

1.Spring AOP(基于AspectJ框架的AOP使用)

1.1实现步骤

导入jar包 添加命名空间
配置bean
<bean id="MyAdvice" class="cn.wang.advice.MyAdvice"></bean>
<bean id="PersonService" class="cn.wang.service.PersonService"></bean>

2.编写目标方法

public class PersonService {
	public boolean save(String name) {
		//自定义异常
		//int num = 3 / 0;
		System.out.println("PersonService...save--"+name);
		return true;
	}
}

3.增强处理类

public class MyAdvice {
	//前置增强
	public void before(JoinPoint joinPoint) {
		//获得类名
		String className = joinPoint.getTarget().getClass().getSimpleName();
		//获得方法名
		String method = joinPoint.getSignature().getName();
		//获得数据
		Object[] args = joinPoint.getArgs();
		System.out.println("在目标前增强"+className+"."+method+","+Arrays.toString(args));
	}
	//后置增强
	public void after(JoinPoint joinPoint,boolean flag){
		System.out.println("在目标后增强:"+flag);
	}
	//最终增强
	public void finalAdvice() {
		System.out.println("最终增强");
	}
	//异常增强
	public void throwAdvice(JoinPoint joinPoint,Exception e) {
		System.out.println("发生异常了" + e.getMessage()+e.getClass().getName());
	}
	//环绕增强
	public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
		System.out.println("。。。。。。。环绕前。。。。。。。。");
		//调用目标
		Object proceed = joinPoint.proceed();
		System.out.println("。。。。。。。环绕后。。。。。。。。");
		return proceed;
	}
}

4.定义切入点

<aop:pointcut  expression="execution(* cn.wang.service..*(..))" id="servicePointCut"/>

5.xml配置文件

<!-- 配置AOP -->
<aop:config>
	<!-- 定位连接点,增强处理作用的位置 -->
	<aop:pointcut  expression="execution(* cn.wang.service..*(..))" id="servicePointCut"/>
	<!-- 定义切面 -->
	<aop:aspect ref="MyAdvice">
		<!-- 前置增强/通知 -->
		<aop:before method="before" pointcut-ref="servicePointCut"/>
		<!-- 后置增强 -->
		<aop:after-returning method="after" pointcut-ref="servicePointCut" returning="flag"/>
		<!-- 异常增强,必须抛出异常 -->
		<aop:after-throwing method="throwAdvice" pointcut-ref="servicePointCut" throwing="e"/>
		<!-- 最终增强 -->
		<aop:after method="finalAdvice" pointcut-ref="servicePointCut"/>
		<!-- 环绕增强 -->
		<aop:around method="around" pointcut-ref="servicePointCut"/>
	</aop:aspect>
</aop:config>	
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值