Spring aop代理

什么叫切面 切点和连接点以及通知所在的类成为切面
切点: Pointcut 是连接点的集合
连接点:execution 最小连接点为方法
通知: 切入连接点的时机

Spring aop 有两种方式 一种是使用xml 另一种是aspectj
首先在xml文件内配置上下文
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:util="http://www.springframework.org/schema/util" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd ">

然后注册业务BEAN

<bean id="bankService" class="springboot.aop.xml.BankServiceImpl">
	</bean>
<!-- bankService为接口 class后为包名.接口实现类名-->

	<bean id="loggerAspect" class="springboot.aop.xml.LoggerAspect"></bean>
<!-- LoggerAspect为类-->

首先使用aop:config标签 确定切面(拦截哪些对象的方法)
表达式:expression=“execution(* springboot.aop.xml..(…))”
第一个* 表示不限制返回值类型
第二个* 表示springboot.aop.xml包下所有的JAVA BEAN
第三个* javabean 所有的方法
(…) 表示对方法的参数没有限制
接着用aop:aspect标签 引入通知类
1.aop:before 前置通知 执行前会返回返回值
2.after method 后置通知 执行后会返回返回值
方法method="logerBefore"与method="logerAfter"皆为loggerPointCut中方法 并且方法参数必须为(JoinPoint jp)
3.后置返回通知 属性 returning 的值必须与 方法logerAfterReturning 返回值的返回值参数名保持一致 方法参数为(JoinPoint jp,Object returnValue)
4.环绕通知 方法参数: logerAround(ProceedingJoinPoint pjp) 可用来修改参数
5.aop:after-throwing 后置异常通知 参数为(JoinPoint jp,Exception exception) 有异常时exception才有值

<aop:config>
		<aop:pointcut expression="execution(* springboot.aop.xml.BankServiceImpl.*(..))" id="loggerPointCut"/>
		<aop:aspect ref="loggerAspect">
			<aop:before method="logerBefore" pointcut-ref="loggerPointCut"/>
			
			<aop:after method="logerAfter" pointcut-ref="loggerPointCut"/>
			<aop:after-returning method="logerAfterReturning" pointcut-ref="loggerPointCut" returning="returnValue"/>
			
			<aop:around method="logerAround" pointcut-ref="loggerPointCut"/>
			
			<aop:after-throwing method="loggerAfterThrowing" pointcut-ref="loggerPointCut"  throwing="exception"/>
			</aop:aspect>

	</aop:config>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值