欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

切入点表达式以及通知类型

程序员文章站 2022-06-02 15:13:42
...

切入点表达式

切入点表达式以及通知类型

通知类型

切入点表达式以及通知类型

获取连接点签名和方法参数

获取连接点签名和方法参数:JoinPoint 和ProceedingJoinPoint.
环绕通知中使用ProceedingJionPoint,其他通知中使用JoinPoint
aop中所有的通知都写在通知类中,所以我就只写一下通知类中的内容

前置通知:
//前置通知
	//joinpoint为链接带点
	//toLongString()获取连接点的签名
	//获取连接点参数
	public boolean before(JoinPoint jp) {
		System.out.println("前置通知"+jp.getSignature().toLongString()+"方法参数"+Arrays.toString(jp.getArgs()) );
		return true;
	}
	
环绕通知

环绕通知中除了参数为ProceedingJoinPoint其他获取连接点签名和方法参数的方法与前置通知中的内容一致我就不再重复了

//环绕通知
	public Object around(ProceedingJoinPoint pjp) {
		System.out.println("around before returning");//前置同通知
		Object r=null;
		try {
			 r= pjp.proceed();//调用目标方法,r时目标方法的返回值
		} catch (Throwable e) {
			
			e.printStackTrace();
			System.out.println("arround after throwing target");//例外通知
		}finally {
			System.out.println("around after target");//最终通知;
			
		}
		System.out.println("around after returning target");//后置通知
		
		return r;
		
	}

获取返回值和异常通知

下面配置文件中after-returning通知中的returning属性就是返回的返回值,要和method指向方法中object类型的参数名一致。
after-throwing中的throwing属性就是抛出的异常要和afterThrowing方法中的Throwable类型参数的参数名一致。

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop 
        https://www.springframework.org/schema/aop/spring-aop.xsd">

    <bean id ="userDao" class="jee.pk1.UserDaoImpl"></bean>
	<bean id ="clientDao" class="jee.pk1.ClientDaoImpl"></bean>
	
	<!-- 这个bean保存通知内容 -->
	<bean id="daoAdvice" class="jee.pk1.DaoAdvice"></bean>
	
	<aop:config>
		<!-- 切面 -->
		<aop:aspect ref="daoAdvice">
		<!-- 切入点 -->
			<aop:pointcut expression="execution(* jee.pk1.*Impl.*(..))" id="daoPointcut"/>
			<!-- 前置通知 -->			
			<aop:after-returning   pointcut-ref="daoPointcut" method="afterReturning" returning="r"/>
			<aop:after-throwing  pointcut-ref="daoPointcut" method="daoPintcut"  throwing="e"/>
		</aop:aspect>
	</aop:config>
</beans>

通知类:

//最终通知
	//r是用于接收返回值的,当spring调用after的时候,spring就会将返回值传回来
	public void after(JoinPoint jp,Object r) {
		System.out.println("after target"+"返回值:"+r);
	}
	
	//例外通知
	//e用于保存目标方法抛出的异常
	public void afterTrowing(JoinPoint jp,Throwable e) {
		System.out.println("after throwing"+"异常:"+e.getMessage());
	}
	
相关标签: ssm框架学习