Spring/Aop代码总结

来源:互联网 发布:npm 网络性能管理 编辑:程序博客网 时间:2024/06/12 23:02

Spring缺省使用JDK动态代理来作为AOP的代理(业务对象实现了至少一个接口),也支持使用CGLIB代理,如果一个业务对象没有实现一个接口,默认会使用CGLIB。

在启动@AspectJ支持的情况下,在application context中定义任意一个带有@Aspect切面(带有@Aspect注解)的bean都会被Spring自动识别并配置在Spring AOP。

在Advice方法中获取目标方法的参数

通过JoinPoint类型的参数获取目标方法的信息,JoinPoint参数代表了织入处理方法的连接点。

//目标函数参数
joinpoint.getArgs();
//目标对象
joinpoint.getTarget();
//代理对象
joinpoint.getThis();

动态切点

一个切面(Aspect)由切点(Pointcut)和增强(Advice)组成,切点提供了连接点的具体类的具体方法,增强提供了横切代码及其织入的位置。单独使用增强时,默认作用于类的所有方法上。
切点的定义由Pointcut表达式和Pointcut签名组成。

@Pointcut(“execution(public * Proxy.Test.Do*(..))”)
private void aspectjMethod(){};

在Advice织入时使用Pointcut签名指定切点:

@Before(“aspectjMethod()”)

定义Pointcut时,可以使用&&、||、!组合多个pointcut。

切点Pointcut由ClassFilter和MethodMatcher构成,通过ClassFilter对应具体的类,通过MethodMatcher过滤方法,有两种方法匹配器:静态方法匹配器和动态方法匹配器。

动态方法切点与静态方法切点的区别是前者使用动态方法匹配器,后者使用静态方法匹配器,区别在于动态方法匹配器会在运行期检查方法的入参的值来匹配方法,每次调用方法时都将检查一次入参,所以对性能影响很大,而静态配置只会匹配一次。

//静态方法匹配器
public boolean matches(Method method ,Class cls)
//动态方法匹配器
public boolean matches(Method method, Class<?> cls, Object[] args)

org.springframework.aop.support.DynamicMethodMatcherPointcut是动态方法切点的抽象基类,默认情况下匹配所有的类。

Aop配置

当业务函数抛出异常后,立即退出,转向After Advice,执行完After Advice,再转到Throwing Advice。
AfterReturning,业务正常退出后,不管是否有返回值,执行此方法。

XML配置

<aop:config>
<aop:aspect id=”aspect” ref=”advicebeanid”>
<aop:pointcut id=”pointUserMgr” expression=”execution(* com.tgb.aop..find(..))”/>
<aop:before method=”doBefore” pointcut-ref=”pointUserMgr”/>
<aop:after method=”doAfter” pointcut-ref=”pointUserMgr”/>
<aop:around method=”doAround” pointcut-ref=”pointUserMgr”/>
<aop:after-returning method=”doReturn” pointcut-ref=”pointUserMgr”/>
<aop:after-throwing method=”doThrowing” throwing=”ex” pointcut-ref=”pointUserMgr”/>
</aop:aspect>
</aop:config>

Around、Before和After的执行顺序取决于在xml中的配置顺序。
Before在业务执行前执行,不能阻止业务的调用。在Around中,当安全性的判断不通过时,可以阻止业务的调用。

Aspect注解配置

// 启用AspectJ对Annotation的支持
<aop:aspectj-autoproxy/>

Around、Before、After、Returning的执行顺序根据注解的顺序而定。有时候修改了注解的顺序,结果没有变化,可能是缓存的原因。

0 0
原创粉丝点击