课程表

Spring 入门

Spring IoC 容器

Spring 依赖注入

Spring Beans 自动装配

Spring 基于注解的配置

Spring 框架

Spring 事务管理

Spring Web MVC 框架

工具箱
速查手册

基于 AOP 的 @AspectJ

当前位置:免费教程 » Java相关 » Spring

@AspectJ 作为通过 Java 5 注释注释的普通的 Java 类,它指的是声明 aspects 的一种风格。通过在你的基于架构的 XML 配置文件中包含以下元素,@AspectJ 支持是可用的。

  1. <aop:aspectj-autoproxy/>

你还需要在你的应用程序的 CLASSPATH 中使用以下 AspectJ 库文件。这些库文件在一个 AspectJ 装置的 ‘lib’ 目录中是可用的,否则你可以在 Internet 中下载它们。

  • aspectjrt.jar

  • aspectjweaver.jar

  • aspectj.jar

  • aopalliance.jar

 声明一个 aspect

Aspects 类和其他任何正常的 bean 一样,除了它们将会用 @AspectJ 注释之外,它和其他类一样可能有方法和字段,如下所示:

  1. package org.xyz;
  2. import org.aspectj.lang.annotation.Aspect;
  3. @Aspect
  4. public class AspectModule {
  5. }

它们将在 XML 中按照如下进行配置,就和其他任何 bean 一样:

  1. <bean id="myAspect" class="org.xyz.AspectModule">
  2. <!-- configure properties of aspect here as normal -->
  3. </bean>

声明一个切入点

一个切入点有助于确定使用不同建议执行的感兴趣的连接点(即方法)。在处理基于配置的 XML 架构时,切入点的声明有两个部分:

  • 一个切入点表达式决定了我们感兴趣的哪个方法会真正被执行。

  • 一个切入点标签包含一个名称和任意数量的参数。方法的真正内容是不相干的,并且实际上它应该是空的。

下面的示例中定义了一个名为 ‘businessService’ 的切入点,该切入点将与 com.tutorialspoint 包下的类中可用的每一个方法相匹配:

  1. import org.aspectj.lang.annotation.Pointcut;
  2. @Pointcut("execution(* com.xyz.myapp.service.*.*(..))") // expression
  3. private void businessService() {} // signature

下面的示例中定义了一个名为 ‘getname’ 的切入点,该切入点将与 com.tutorialspoint 包下的 Student 类中的 getName() 方法相匹配:

  1. import org.aspectj.lang.annotation.Pointcut;
  2. @Pointcut("execution(* com.tutorialspoint.Student.getName(..))")
  3. private void getname() {}

声明建议

你可以使用 @{ADVICE-NAME} 注释声明五个建议中的任意一个,如下所示。这假设你已经定义了一个切入点标签方法 businessService():

  1. @Before("businessService()")
  2. public void doBeforeTask(){
  3. ...
  4. }
  5. @After("businessService()")
  6. public void doAfterTask(){
  7. ...
  8. }
  9. @AfterReturning(pointcut = "businessService()", returning="retVal")
  10. public void doAfterReturnningTask(Object retVal){
  11. // you can intercept retVal here.
  12. ...
  13. }
  14. @AfterThrowing(pointcut = "businessService()", throwing="ex")
  15. public void doAfterThrowingTask(Exception ex){
  16. // you can intercept thrown exception here.
  17. ...
  18. }
  19. @Around("businessService()")
  20. public void doAroundTask(){
  21. ...
  22. }

你可以为任意一个建议定义你的切入点内联。下面是在建议之前定义内联切入点的一个示例:

  1. @Before("execution(* com.xyz.myapp.service.*.*(..))")
  2. public doBeforeTask(){
  3. ...
  4. }

基于 AOP 的 @AspectJ 示例

为了理解上面提到的关于基于 AOP 的 @AspectJ 的概念,让我们编写一个示例,可以实现几个建议。为了在我们的示例中使用几个建议,让我们使 Eclipse IDE 处于工作状态,然后按照如下步骤创建一个 Spring 应用程序:

步骤 描述
1 创建一个名为 SpringExample 的项目,并且在所创建项目的 src 文件夹下创建一个名为 com.tutorialspoint 的包。
2 使用 Add External JARs 选项添加所需的 Spring 库文件,就如在 Spring Hello World Example 章节中解释的那样。
3 在项目中添加 Spring AOP 指定的库文件 aspectjrt.jar, aspectjweaver.jaraspectj.jar
4 com.tutorialspoint 包下创建 Java 类 LoggingStudentMainApp
5 src 文件夹下创建 Beans 配置文件 Beans.xml
6 最后一步是创建所有 Java 文件和 Bean 配置文件的内容,并且按如下解释的那样运行应用程序。

这里是 Logging.java 文件的内容。这实际上是 aspect 模块的一个示例,它定义了在各个点调用的方法。

  1. package com.tutorialspoint;
  2. import org.aspectj.lang.annotation.Aspect;
  3. import org.aspectj.lang.annotation.Pointcut;
  4. import org.aspectj.lang.annotation.Before;
  5. import org.aspectj.lang.annotation.After;
  6. import org.aspectj.lang.annotation.AfterThrowing;
  7. import org.aspectj.lang.annotation.AfterReturning;
  8. import org.aspectj.lang.annotation.Around;
  9. @Aspect
  10. public class Logging {
  11. /** Following is the definition for a pointcut to select
  12. * all the methods available. So advice will be called
  13. * for all the methods.
  14. */
  15. @Pointcut("execution(* com.tutorialspoint.*.*(..))")
  16. private void selectAll(){}
  17. /**
  18. * This is the method which I would like to execute
  19. * before a selected method execution.
  20. */
  21. @Before("selectAll()")
  22. public void beforeAdvice(){
  23. System.out.println("Going to setup student profile.");
  24. }
  25. /**
  26. * This is the method which I would like to execute
  27. * after a selected method execution.
  28. */
  29. @After("selectAll()")
  30. public void afterAdvice(){
  31. System.out.println("Student profile has been setup.");
  32. }
  33. /**
  34. * This is the method which I would like to execute
  35. * when any method returns.
  36. */
  37. @AfterReturning(pointcut = "selectAll()", returning="retVal")
  38. public void afterReturningAdvice(Object retVal){
  39. System.out.println("Returning:" + retVal.toString() );
  40. }
  41. /**
  42. * This is the method which I would like to execute
  43. * if there is an exception raised by any method.
  44. */
  45. @AfterThrowing(pointcut = "selectAll()", throwing = "ex")
  46. public void AfterThrowingAdvice(IllegalArgumentException ex){
  47. System.out.println("There has been an exception: " + ex.toString());
  48. }
  49. }

下面是 Student.java 文件的内容:

  1. package com.tutorialspoint;
  2. public class Student {
  3. private Integer age;
  4. private String name;
  5. public void setAge(Integer age) {
  6. this.age = age;
  7. }
  8. public Integer getAge() {
  9. System.out.println("Age : " + age );
  10. return age;
  11. }
  12. public void setName(String name) {
  13. this.name = name;
  14. }
  15. public String getName() {
  16. System.out.println("Name : " + name );
  17. return name;
  18. }
  19. public void printThrowException(){
  20. System.out.println("Exception raised");
  21. throw new IllegalArgumentException();
  22. }
  23. }

下面是 MainApp.java 文件的内容:

  1. package com.tutorialspoint;
  2. import org.springframework.context.ApplicationContext;
  3. import org.springframework.context.support.ClassPathXmlApplicationContext;
  4. public class MainApp {
  5. public static void main(String[] args) {
  6. ApplicationContext context =
  7. new ClassPathXmlApplicationContext("Beans.xml");
  8. Student student = (Student) context.getBean("student");
  9. student.getName();
  10. student.getAge();
  11. student.printThrowException();
  12. }
  13. }

下面是配置文件 Beans.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:aop="http://www.springframework.org/schema/aop"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  7. http://www.springframework.org/schema/aop
  8. http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
  9.  
  10. <aop:aspectj-autoproxy/>
  11.  
  12. <!-- Definition for student bean -->
  13. <bean id="student" class="com.tutorialspoint.Student">
  14. <property name="name" value="Zara" />
  15. <property name="age" value="11"/>
  16. </bean>
  17.  
  18. <!-- Definition for logging aspect -->
  19. <bean id="logging" class="com.tutorialspoint.Logging"/>
  20.  
  21. </beans>

一旦你已经完成的创建了源文件和 bean 配置文件,让我们运行一下应用程序。如果你的应用程序一切都正常的话,这将会输出以下消息:

  1. Going to setup student profile.
  2. Name : Zara
  3. Student profile has been setup.
  4. Returning:Zara
  5. Going to setup student profile.
  6. Age : 11
  7. Student profile has been setup.
  8. Returning:11
  9. Going to setup student profile.
  10. Exception raised
  11. Student profile has been setup.
  12. There has been an exception: java.lang.IllegalArgumentException
  13. .....
  14. other exception content
转载本站内容时,请务必注明来自W3xue,违者必究。
 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号