Spring——12 AspectJ

本文详细介绍了如何使用AspectJ结合Spring AOP实现方法拦截,包括前置、后置、环绕通知等,通过具体示例代码展示了配置过程及注意事项。

使用 AspectJ 方式实现

1. 新建类,不用实现

类中方法名任意

public class MyAdvice { 
	public void mybefore(String name1,int age1){
	System.out.println("前置"+name1 );
} 
public void mybefore1(String name1){ 
	System.out.println("前置:"+name1); 
} 
public void myaftering(){ 
	System.out.println("后置 2"); 
} 
public void myafter(){ 
	System.out.println("后置 1"); 
} 
public void mythrow(){ 
	System.out.println("异常"); 
} 
public Object myarround(ProceedingJoinPoint p) throws Throwable{ 
	System.out.println("执行环绕"); 
	System.out.println("环绕-前置"); 
	Object result = p.proceed(); 
	System.out.println("环绕后置"); 
	return result; 
	}
}

2.配置 spring 配置文件

  1. aop:after/ 标签—— 后置通知,是否出现异常都执行
  2. aop:after-returing/ 标签——后置通知,只有当切点正确执行时
    执行
  3. aop:after/ 和 aop:after-returing/ 和aop:after-throwing/ 标签——执行顺序和配置顺序有关
  4. execution() 括号不能扩上 args
  5. 中间使用 and 不能使用&& 由 spring 把 and 解析成&&
  6. args(名称) 名称自定义的.顺序和 demo1(参数,参数)对应
  7. aop:before/ 标签 arg-names=” 名 称 ” 名 称 来 源 于expression=”” 中 args(),名称必须一样
    ①args() 有几个参数,arg-names 里面必须有几个参数
    ②arg-names=”” 里面名称必须和通知方法参数名对应
<aop:config> 
	<aop:aspect ref="myadvice"> 
		<aop:pointcut expression="execution(* com.youdian.test.Demo.demo1(String,int)) and args(name1,age1)" id="mypoint"/> 
		<aop:pointcut expression="execution(*com.youdian.test.Demo.demo1(String)) and args(name1)" id="mypoint1"/>
		<aop:before method="mybefore" pointcut-ref="mypoint" arg-names="name1,age1"/> 				
		<aop:before method="mybefore1" pointcut-ref="mypoint1" arg-names="name1"/>
		<!-- <aop:after method="myafter" pointcut-ref="mypoint"/> 
		<aop:after-returning method="myaftering" pointcut-ref="mypoint"/> 
		<aop:after-throwing method="mythrow" pointcut-ref="mypoint"/> 
		<aop:around method="myarround" pointcut-ref="mypoint"/>--> 			
	</aop:aspect> 
</aop:config>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值