Spring AOP使用心得
畢竟是***次使用Spring AOP,按照Reference中的介紹,準(zhǔn)備使用Annotation來完成對AOP的配置。來看一下我做的步驟:
一、需要使用Spring2.0的jar包,現(xiàn)在已經(jīng)發(fā)布正式版的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
- default-autowire="byName" default-lazy-init="true">
2、“如果使用Java 5的話,推薦使用Spring提供的@AspectJ切面支持,通過這種方式聲明Spring AOP中使用的切面。 "@AspectJ"使用了Java 5的注解,可以將切面聲明為普通的Java類?!薄猄pring reference
3、為了使用Spring AOP的Annotation,在配置文件中加入<aop:aspectj-autoproxy />。
4、編寫切面類:
- public class ArticleRemoteAccountsService {
- /** *//**
- * 在發(fā)帖成功之后,給用戶銀幣賬戶沖值
- *
- * @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?)這里就不累訴了。同時要注意的如何得到參數(shù)的問題,寫法參考如上。
【編輯推薦】