温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Spring AOP的用法

发布时间:2021-07-13 18:37:33 来源:亿速云 阅读:122 作者:chen 栏目:编程语言

本篇内容介绍了“Spring AOP的用法”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

毕竟是***次使用Spring AOP,按照Reference中的介绍,准备使用Annotation来完成对AOP的配置。来看一下我做的步骤:

一、需要使用Spring2.0的jar包,现在已经发布正式版的2.0了,可以从http://www.springframework.org/上下载到***的2.0版本。加入到项目的classpath中去。

二、需要在配置文件中启用新的spring2.0的schema或者是dtd。  

1、在Spring的xml配置文件中加入新的schema:

  1. <beans xmlns="http://www.springframework.org/schema/beans" 

  2.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 

  3.     xmlns:aop="http://www.springframework.org/schema/aop" 

  4.     xmlns:tx="http://www.springframework.org/schema/tx" 

  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans/spring-beans-2.0.xsd  

  6.            http://www.springframework.org/schema/aop                           http://www.springframework.org/schema/aop/spring-aop-2.0.xsd  

  7.            http://www.springframework.org/schema/tx                                 http://www.springframework.org/schema/tx/spring-tx-2.0.xsd"  

  8.     default-autowire="byName" default-lazy-init="true"> 

2、“如果使用Java 5的话,推荐使用Spring提供的@AspectJ切面支持,通过这种方式声明Spring AOP中使用的切面。 "@AspectJ"使用了Java 5的注解,可以将切面声明为普通的Java类。”——Spring reference

3、为了使用Spring AOP的Annotation,在配置文件中加入<aop:aspectj-autoproxy />。

4、编写切面类:

  1. public class ArticleRemoteAccountsService {  

  2.    


  3.     /** *//**  

  4.      * 在发帖成功之后,给用户银币账户冲值  

  5.      *   

  6.      * @param arg  

  7.      * @throws AccountsException  

  8.      * @throws InstantiationException  

  9.      * @throws IllegalAccessException  

  10.      */  

  11.     @After("execution(* com.company.ArticleManager.saveArticle(..))"  

  12.             + " && args(arg)")  

  13.     public void exSilByPost(Article arg) throws AccountsException,  

  14.             InstantiationException, IllegalAccessException {  


  15.         if (arg.getLastUpdateTime() == null  

  16.                 && arg.getArticleByParentId() == null  

  17.                 && arg.getArticleByRootId() == null) {  

  18.             // TODO 主题帖  


  19.         } else if (arg.getLastUpdateTime() == null  

  20.                 && (arg.getArticleByParentId() != null || arg  

  21.                         .getArticleByRootId() != null)) {  

  22.             // TODO  回帖  


  23.         }  


  24.     }  


  25. }  

这里需要注意的是使用Annotation的Poincut语法,execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern) throws-pattern?)这里就不累诉了。同时要注意的如何得到参数的问题,写法参考如上。

“Spring AOP的用法”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI