思诚科技 seecen LOGO
咨询热线:0791-87557233
 您现在的位置:  首页 > Java框架 

Spring 2.X 中AOP的使用浅析

来源:网络    更新时间:2014-12-16


本文转自Javablog,文中内容不代表本站观点,仅提供参考。

  和Spring1.X相比,Spring2.X使用ASPectJ的语法来声明AOP,这使得它更“标准”,更灵活了。还是那句话,如果你不了解AspectJ并且打算使用Spring2.X的AspectJ式AOP,那就学学AspectJ吧,这方面的书还是很多了。

  Spring2.X下的切面有两种实现方式,一种是以Java文件定义切面(其只是普通的Java类),然后在配置文件中声明定义的切面;另一种是在Java类中引入和AOP相关的元数据(注释)。

  先介绍第一种配置方式。需要指出的是,Spring2.X的beans名称空间和Spring1.X有所不同,它采用了Schema而不是DTD(也可采用DTD方式,具体的请参考文档)。还是引入毫无意义的日志切面,定义的切面类LogingAspect如下:

publicclassLogingAspect{
 publicvoidlogMethod(JoinPointjp){
  System.err.println(jp.getTarget().getClass());
  System.err.println(jp.getSignature().getName());
 }
}
  同时在配置文件中如下配置:

<beanid="logAspectTarget"class="Hibernatesample.service.util.LogingAspect">
</bean>
<aop:config>
<aop:aspectid="logAspect"ref="logAspectTarget">
<aop:pointcutid="businessService"expression="execution(*hibernatesample.service.*.*(..))"/>
<aop:afterpointcut-ref="businessService"method="logMethod"/>
</aop:aspect>
</aop:config>
  对于上面的切面,切入点businessService是在配置文件中声明的,其表达式采用了AspectJ的语法,LogingAspect类中logMethod(JoinPointjp)方法根据配置文件信息可知其是after通知,方法的JoinPoint参数不是必须的,它是来自于AspectJ的实用类,这里用它不过输出一些和连接点有关的信息。当然,在Spring2.X中,切入点和通知能更灵活的使用,我们可以如AspectJ一样传递参数给通知。如果需要在Service中引入事务功能,需要如下配置事务通知:

<tx:adviceid="txAdvice"transaction-manager="transactionManager">
<tx:attributes>
<tx:methodname="get*"read-only="true"/>
<tx:methodname="find*"read-only="true"/>
<tx:methodname="*"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcutid="demoServiceMethods"expression="execution(*hibernatesample.service.*.*(..))"/>
<aop:advisoradvice-ref="txAdvice"pointcut-ref="demoServiceMethods"/>
<aop:aspectid="logAspect"ref="logAspectTarget">
<aop:pointcutid="businessService"expression="execution(*hibernatesample.service.*.*(..))"/>
<aop:afterpointcut-ref="businessService"method="logMethod"/>
</aop:aspect>
</aop:config>
  完成上面的工作相当于完成了Spring1.X的自动代理。我们接下来需要定义的任何ServiceBean都可以很纯粹很纯粹了:

<beanid="accountService"class="hibernatesample.service.impl.AccountServiceImpl">
<propertyname="accountDAO"ref="accountDAO"></property>
</bean>
  第二种实现AOP的方式和第一种相比,只是在LogingAspect中加入了注释,而省去了配置文件中和LogingAspect相关的配置。重新编写的LogingAspect如下:

@Aspect

publicclassLogingAspect{
@Pointcut("execution(*hibernatesample.service.*.*(..))")
publicvoidbusinessService(){}
@After("businessService()")
publicvoidlogMethod(JoinPointjp){
 System.err.println(jp.getTarget().getClass());
 System.err.println(jp.getSignature().getName());

  • 上一篇文章:

  • 下一篇文章:
  •  

    0791-87557233

    重视每个来电 珍惜您的时间
    思诚者开发沙龙
    江西思诚科技有限公司  赣ICP备17006097号  CopyRight©2014 - 2020