SpringAOP 增强

[b]AOP步骤[/b]
通过切点和增强定位到连接点上
在增强中编写切面代码

[b]Spring增强类型[/b]
前置增强 - org.springframework.aop.BeforeAdvice(MethodBeforeAdvice可用)
后置增强 - org.springframework.aop.AfterReturningAdvice
环绕增强 - org.springframework.intercept.MethodInterceptor
异常抛出增强 - org.springframework.aop.ThrowsAdvice
引介增强 - org.springframework.aop.IntroductionInterceptor

[b]ProxyFactoryBean配置代理[/b]
<bean id="myAdvice" class="com.test.MyBeforeAdvice" />
<bean id="target" class="com.test.NativeWaiter" />
<bean id="waiter" class="com.springframework.aop.framework.ProxyFactoryBean"
p:proxyInterfaces="com.test.Waiter"
p:interceptorNames="myAdvice"
p:target-ref="target"
/>

[b]ProxyFactoryBean常用属性[/b]
target 目标类
proxyInterface 代理接口列表
interceptorNames 增强列表
singleton 返回的代理是否是单实例,默认单实例
optimize 为true时,强制使用CGLib代理
proxyTargetClass 是否对类进行代理,为true时,使用CGLib代理

[b]前置增强[/b]
public class MyBeforeAdvice implements MethodBeforeAdvice{
public void before(Method method, Object[] args, Object obj) throws Throwable{//...}
}
method 目标类方法
args 目标方法入参
obj 目标类实例
before()方法发生异常时,将阻止目标类方法的执行

[b]后置增强[/b]
public class MyAfterAdvice implements AfterReturningAdvice{
public void afterReturning(Object returnObj, Method method,Object[] args,Object obj) throws Throwable{//...}
}
returnObj 目标类返回结果
method 目标类方法
args 目标方法入参
obj 目标类实例
afterReturning抛出异常时,如果是目标方法声明的异常,则归并到目标方法中;如果不是目标方法声明的异常,Spring将其转为运行时异常抛出

[b]环绕增强[/b]
public class MyInterceptor implements MethodInterceptor{
public Object invoke(MethodInvocation invocation) throws Throwable{
Object[] args = invocation.getArguments();
//...
Object obj = invocation.proceed();
//...
return obj;
}
}

[b]异常抛出增强[/b]
public class MyThrowsAdvice implements ThrowsAdvice{
public void afterThrowing(Method method, Object[] args, Object target, Exception e) throws Throwable{//...}
}
ThrowsAdvice是一个接口标识,未定义任何方法
增强方法的签名必须是void afterThrowing(Method method,Object[] args, Object target, Throwable e)
Object target为可选(要么3个入参,要么0个入参)
可以定义多个afterThrowing()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值