Spring2.0 AOP使用心得(一)

      正在做的项目中有一个类似积分的需求,比如用户在讨论区发帖后,需要给一定的积分这样的需求。因为需求是变化的,同时为了使已经写好的发帖代码不被入侵,所以考虑使用Spring2.0 AOP来实现这个功能。
      毕竟是第一次使用Spring2.0的AOP,按照Reference中的介绍,准备使用Annotation来完成对AOP的配置。来看一下我做的步骤:
      一、需要使用Spring2.0的jar包,现在已经发布正式版的2.0了,可以从http://www.springframework.org/  上下载到最新的2.0版本。加入到项目的classpath中去。
      二、需要在配置文件中启用新的spring2.0的schema或者是dtd。   
      1、在Spring的xml配置文件中加入新的schema:
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi
="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop
="http://www.springframework.org/schema/aop"
    xmlns:tx
="http://www.springframework.org/schema/tx"
    xsi:schemaLocation
="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd"

    default-autowire
="byName" default-lazy-init="true">
       2、“如果使用Java 5的话,推荐使用Spring提供的@AspectJ切面支持,通过这种方式声明Spring AOP中使用的切面。 "@AspectJ"使用了Java 5的注解,可以将切面声明为普通的Java类。”——Spring reference
      3、为了使用AOP的Annotation,在配置文件中加入<aop:aspectj-autoproxy />。
      4、编写切面类:
@Aspect
public class ArticleRemoteAccountsService {
 


    
/**
     * 在发帖成功之后,给用户银币账户冲值
     * 
     * 
@param arg
     * 
@throws AccountsException
     * 
@throws InstantiationException
     * 
@throws IllegalAccessException
     
*/

    @After(
"execution(* com.company.ArticleManager.saveArticle(..))"
            
+ " && args(arg)")
    
public void exSilByPost(Article arg) throws AccountsException,
            InstantiationException, IllegalAccessException 
{

        
if (arg.getLastUpdateTime() == null
                
&& arg.getArticleByParentId() == null
                
&& arg.getArticleByRootId() == null{
            
// TODO 主题帖

        }
 else if (arg.getLastUpdateTime() == null
                
&& (arg.getArticleByParentId() != null || arg
                        .getArticleByRootId() 
!= null)) {
            
// TODO  回帖

        }


    }


}

这里需要注意的是使用Annotation的Poincut语法,
execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern) throws-pattern?)
这里就不累诉了。
同时要注意的如何得到参数的问题,写法参考如上。
posted on 2006-10-20 11:02 旱头憨脑 阅读(961) 评论(0)  编辑  收藏 所属分类: j2ee

只有注册用户登录后才能发表评论。


网站导航: