Spring(2)--Aop面向切面编程

本文深入解析Spring AOP的实现机制,包括前置、后置、异常、最终和环绕增强的使用方法,通过XML和注解两种方式展示如何配置切面,为开发者提供全面的AOP应用指南。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SpringAOP
AOP切入点

public class UserSerciceLogger(){
	//前置增强
		public void before(JoinPoint jp){
			Syso("调用"+jp.getTarget()+"的"+jp.getSignature().getName()+"方法,方法入参:"+Arrays.toString(jp.getArgs()));
		}
	//后置增强
		public void after(JoinPoint jp,Object result){
			Syso("调用"+jp.getTarget()+"的"+jp.getSignature().getName()+"方法.方法返回值:"+result);
		}
		//异常抛出增强(相当于异常处理的finally块)
		public void afterThrowing(JoinPoint jp,RuntimeException e){
		
		}
		//最终增强
		public void afterLog(JoinPoint jp){
		}
		//环绕增强
		public Object around(ProceedingJoinPoint jp){
			Object result=jp.proceed();//执行目标方法并获得返回值
			return result;
		}
}

appliactionContext.xml

<!--根据切入点的类创建Bean-->
<bean id="theLogger" calss="cn.a.aop.UserSerciceLogger"></bean>
<!--aop的配置节点-->
<aop:config>
<!--切入点-->
	<aop:pointcut id="pointcut" expression="execution(public void xxx(xxx))"/><!--匹配方法  上图有详细说明-->
	<aop:aspect ref="theLogger"><!--theLogger是切入点的类创建的bean-->
		<!--前置增强-->
			<aop:before method="before" pointcut-ref="pointcut"></aop:before>
			<!--后置增强-->
			<aop:after-returning method="after"  pointcut-ref="pointcut" returning="result"/>
			<!--异常抛出增强-->
			<aop:after-throwing method="afterThrowing" pointcut-ref="pointcut" throwing="e"/>
			<!--最终增强-->
			<aop:after method="afterLog" pointcut-ref="pointcut"/>
			<!--环绕增强-->
			<aop:around method="around" pointcut-ref="pointcut"/>
	</aop:aspect>
</aop:config>

调用

ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
ctx.getBean("bean节点的名字");//相当于创建对象

使用注解定义切面

@Aspect
public class UserSerciceLogger(){
	//前置增强
	@Before("execution(     )")
		public void before(JoinPoint jp){
			Syso("调用"+jp.getTarget()+"的"+jp.getSignature().getName()+"方法,方法入参:"+Arrays.toString(jp.getArgs()));
		}
	//后置增强
	@AfterRuturning(   pointcut = "execution(     )"  , returning="result")
		public void after(JoinPoint jp,Object result){
			Syso("调用"+jp.getTarget()+"的"+jp.getSignature().getName()+"方法.方法返回值:"+result);
		}
		
		//异常抛出增强(相当于异常处理的finally块)
		@AfterThrowing(   pointcut = "execution(     )"  , throwing="e")
		public void afterThrowing(JoinPoint jp,RuntimeException e){
		
		}
		//最终增强
		@After(   pointcut = "execution(     )" )
		public void afterLog(JoinPoint jp){
		}
		//环绕增强
		@Around(   pointcut = "execution(     )"  , returning="result")
		public Object around(ProceedingJoinPoint jp){
			Object result=jp.proceed();//执行目标方法并获得返回值
			return result;
		}
}

AppliactionContext.xml

<context:component-scan base-package="包名"/>
<bean class="UserSerciceLogger"/>
<aop:aspectj-autoproxy/>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值