您的位置:首页 > 编程语言 > Java开发

Spring学习总结7(AOP-基于XML)

2011-04-10 18:07 603 查看
Spring也提供了AOP的实现,切面就和常规的Java对象一样被定义成application context中的一个bean。

对象的字段和方法提供了状态和行为信息。

XML文件则提供了切入点和通知信息。

声明切面

public class LogInterceptor{
public void before(){
//...
}

public void after(Object retVal){
//...
}

public void throw(Throwable ex){
//...
}

public void last(){
//...
}

public void around(ProceedingJoinPoint pj) throws Throwable {
//...
}

}


在XML配置切面

<bean id="logInterceptor" class="com.bjsxt.aop.LogInterceptor">
</bean>

<aop:config>
<aop:aspect id="logAspect" ref="logInterceptor">
<!-- 在通知时直接声明切入点 -->
<aop:before method="before" pointcut="execution(public * com.bjsxt.service..*.add(..))" />

<!-- 声明切入点 -->
<aop:pointcut id="businessService"
expression="execution(* com.xyz.myapp.service.*.*(..))"/>
<!-- 前置通知 -->
<aop:before pointcut-ref="businessService" method="before2"/>
<!-- 后置通知 -->
<aop:after-returning pointcut-ref="businessService" method="before2" returning="retVal" />
<!-- 异常通知 -->
<aop:after-throwing pointcut-ref="businessService" method="throw" throwing="ex" />
<!-- 最终通知 -->
<aop:after pointcut-ref="businessService" method="last" />
<!-- 环绕通知 -->
<aop:around pointcut-ref="businessService" method="around" />

</aop:aspect>
</aop:config>


Advisor

advisor就像一个小的自包含的切面,这个切面只有一个通知。

<aop:config>

<aop:pointcut id="businessService"
expression="execution(* com.xyz.myapp.service.*.*(..))"/>

<aop:advisor
pointcut-ref="businessService"
advice-ref="tx-advice"/>

</aop:config>

<tx:advice id="tx-advice">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>


Spring AOP与AspectJ的选择

Spring AOP比完全使用AspectJ更加简单, 因为它不需要引入AspectJ的编译器/织入器到你开发和构建过程中。

如果你仅仅需要在Spring bean上通知执行操作,那么Spring AOP是合适的选择。

如果你需要通知domain对象或其它没有在Spring容器中管理的任意对象,那么你需要使用AspectJ。

如果你想通知除了简单的方法执行之外的连接点(如:调用连接点、字段get或set的连接点等等), 也需要使用AspectJ。

基于XML还是注解

XML:

显然如果你不是运行 在Java 5上,XML风格是最佳选择。

XML风格对现有的Spring用户来说更加习惯。它可以使用在任何Java级别中 (参考连接点表达式内部的命名连接点,虽然它也需要Java 5+) 并且通过纯粹的POJO来支持。当使用AOP作为工具来配置企业服务时XML会是一个很好的选择。 (一个好的例子是当你认为连接点表达式是你的配置中的一部分时,你可能想单独更改它) 对于XML风格,从你的配置中可以清晰的表明在系统中存在那些切面。

注解:

@AspectJ风格支持其它的实例模型以及更丰富的连接点组合。它具有将切面保持为一个模块单元的优点。@AspectJ切面能被Spring AOP和AspectJ两者都理解。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: