日期:2014-05-17  浏览次数:20739 次

一步一步学习spring(八)——Spring AOP之XML风格和AspectJ风格(注解形式)的比较
               Spring AOP和AspectJ的比较
   
    Spring AOP比完全使用AspectJ更加简单, 因为它不需要引入AspectJ的编译器/织
入器到你开发和构建过程中。 如果你仅仅需要在Spring bean上通知执行操作,那么Spring
AOP是合适的选择。 如果你需要通知domain对象或其它没有在Spring容器中管理的任意对
象,那么你需要使用AspectJ。 如果你想通知除了简单的方法执行之外的连接点(如:调用
连接点、字段get或set的连接点等等), 也需要使用AspectJ。

     XML风格 = 采用声明形式实现Spring AOP
    AspectJ风格 = 采用注解形式实现Spring AOP


    先前写的了两篇博文,描述了 XML风格 和 AspectJ风格的使用示例,有兴趣可看看:

    XML风格:http://xtu-xiaoxin.iteye.com/admin/blogs/630787
   AspectJ风格:http://xtu-xiaoxin.iteye.com/blog/630206

    1. 首先,对注解的支持是在Java5版本以后,所以,如果你使用的是java5版本以下的JVM,
不用考虑,必须选择XML风格 (XML配置形式的),而非注解形式(AspectJ风格)的。

    2. 使用XML风格,则所有的切面、切点、通知等配置都写在一个或几个Spring配置文件里。
这样的好处是,从配置文件中,就可以很清晰的看出系统中的有哪些切面,某个切面里使用那个的
通知(advice)以及通知(advice)作用的切点。而在AspectJ风格中,在java程序中标识切面
则显得凌乱、模糊。

    在什么情况下使用注解形式的AOP?或者说使用注解来实现AOP有哪些优点呢?
   
    1. XML风格的AOP仅仅支持"singleton"切面实例模型,而采用AspectJ风格的AOP则
没有这个限制。

    2.XML风格的AOP中是不支持命名连接点的声明,而采用AspectJ风格的AOP则没有这个限制。不太理解的看下面实例代码:
  在@AspectJ风格中我们可以编写如下的内容:
  
@Pointcut(execution(* get*()))
                public void propertyAccess() {}
                
                @Pointcut(execution(org.xyz.Account+ *(..))
                public void operationReturningAnAccount() {}
                
                @Pointcut(propertyAccess() && operationReturningAnAccount())
            public void accountPropertyAccess() {}


在XML风格中,我们不能使用'&&'字符来连接命名连接点,如下:
<aop:pointcut id="propertyAccess"
                expression="execution(* get*())"/>
                
                <aop:pointcut id="operationReturningAnAccount"
            expression="execution(org.xyz.Account+ *(..))"/>
            <!-- 错误的配置  -->
          <aop:pointcut id="accountPropertyAccess"
            expression="propertyAccess && operationReturningAnAccount"/>



注意: XML风格AOP虽然不支命名连接点的声明,但是,可以使用如下形式处理,如下配置:
<aop:pointcut id="propertyAccess"
                expression="execution(* get*())"/>
   <aop:pointcut id="operationReturningAnAccount"
            expression="execution(org.xyz.Account+ *(..))"/>
    <aop:pointcut id="accountPropertyAccess"
            expression="execution(* get*()) and execution(org.xyz.Account+ *(..))"/>


    这里对Spring中使用AOP两种不同的配置方式作了个简单的比较,希望对大家有点用处。
1 楼 FeiXing2008 2010-04-09  
不错, 是个好东西 ,收了
2 楼 yfnok 2010-04-18  
再接再厉啊,向你学习中