Spring(二)AOP

概念

AOP(Aspect Oriented Programming)

  1. 切点(pointcut):原有功能
  2. 前置通知(before advice):切点前执行的功能
  3. 后置通知(after advice): 在切点之后执行的功能
  4. 异常通知(throws advice):切点执行过程中出现异常时触发.

实现方式

spring 提供了2 种AOP 实现方式
1.Schema_based
每个通知都需要实现接口或类,在aop:config中配置
2. AspectJ
不需要实现接口或类,在aop:config子标签
aop:aspect中配置

Schema-based 实现

1.环境配置
在这里插入图片描述
2. 新建通知类
前置通知:
2.1 实现MethodBeforeAdvice接口
2.2 重写的before方法有三个参数
arg0: Method类型切点对象
arg1: 切点参数
arg2:切点所在对象

public class MyBeforeAdvice implements
MethodBeforeAdvice {
@Override
public void before(Method arg0, Object[] arg1, Object
arg2) throws Throwable {
System.out.println("执行前置通知");
}
}

后置通知
2.1实现AfterReturningAdvice接口
2.2 重写的afterReturning方法有三个参数
arg0:切点返回值
arg1: Method类型切点对象
arg2: 切点参数
arg3:切点所在对象

public class MyAfterAdvice implements
AfterReturningAdvice {
@Override
public void afterReturning(Object arg0, Method arg1,
Object[] arg2, Object arg3) throws Throwable {
System.out.println("执行后置通知");
}
}
  1. 配置spring文件
    3.1 引入aop命名空间
    3.2 配置通知类的
    3.3 通配符*,匹配任一包,类或方法
    (…)匹配任一方法参数
<?xml version="1.0" encoding="UTF-8"?>
<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/sc
hema/beans
http://www.springframework.org/schema/beans/spring-be
ans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.
xsd">
<!-- 配置通知类对象,在切面中引入-->
<bean id="mybefore"
class="advice.MyBeforeAdvice"></bean>
<bean id="myafter"
class="advice.MyAfterAdvice"></bean>
<!-- 配置切面-->
<aop:config>
<!-- 配置切点-->
<aop:pointcut expression="execution(*
test.Demo.demo2())" id="mypoint"/>
<!-- 通知-->
<aop:advisor advice-ref="mybefore"
pointcut-ref="mypoint"/>
<aop:advisor advice-ref="myafter"
pointcut-ref="mypoint"/>
</aop:config>
<!-- 配置Demo 类,测试使用-->
<bean id="demo" class="test.Demo"></bean>
</beans>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值