欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java的Spring框架下的AOP编程模式示例

程序员文章站 2024-03-07 15:24:21
spring框架的关键组件是面向方面编程(aop)框架。面向方面的编程不仅打破程序逻辑分成不同的部分称为所谓的担忧。跨越多个点的应用程序的功能被称为横切关注点和这些横切关注...

spring框架的关键组件是面向方面编程(aop)框架。面向方面的编程不仅打破程序逻辑分成不同的部分称为所谓的担忧。跨越多个点的应用程序的功能被称为横切关注点和这些横切关注点是从应用程序的业务逻辑概念上区分开来。还有像日志记录,审计,声明性事务,安全性和高速缓存等方面的各种常见的好例子

模块化的oop中的关键单元是类,而在aop中模块化的单元则是切面。依赖注入可以帮助你从对方解耦应用程序对象和aop可以帮助你从他们影响的对象分离横切关注点。 aop是一样的编程语言如perl,.net,java和其他触发器。

spring aop模块提供了拦截器拦截的应用程序,例如,执行一个方法时,可以之前或之后执行的方法添加额外的功能。

aop术语:
在我们开始使用aop之前,先熟悉aop的概念和术语。这些条款是不特定于spring,问题都是有关aop。
建议的类型
spring方面可以用5种下面提到的建议:

Java的Spring框架下的AOP编程模式示例

自定义方面实现

spring基于xml模式的aop
需要如下所述导入spring aop架构:

<?xml version="1.0" encoding="utf-8"?>
<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"
  xsi:schemalocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
  http://www.springframework.org/schema/aop 
  http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

  <!-- bean definition & aop specific configuration -->

</beans>

还需要在以下应用程序classpath中的aspectj库。这些库可以在aspectj的安装'lib'目录可用,可以从互联网上下载它们。

  • aspectjrt.jar
  • aspectjweaver.jar
  • aspectj.jar

声明一个切面
一个方面是使用<aop:aspect>元素中声明,并且支持bean是使用ref属性如下参考:

<aop:config>
  <aop:aspect id="myaspect" ref="abean">
  ...
  </aop:aspect>
</aop:config>

<bean id="abean" class="...">
...
</bean>

这里的“abean”将配置和依赖注入,就像任何其他的spring bean,我们已经在前面的章节看到。

声明一个切入点
一个切入点有助于确定与不同要执行的连接点的利息(即方法)。同时与xml架构基础的配置工作,切入点将被定义如下:

<aop:config>
  <aop:aspect id="myaspect" ref="abean">

  <aop:pointcut id="businessservice"
   expression="execution(* com.xyz.myapp.service.*.*(..))"/>
  ...
  </aop:aspect>
</aop:config>

<bean id="abean" class="...">
...
</bean>

下面的示例定义一个名为'的businessservice“切入点将匹配可用的软件包com.yiibai下执行getname()方法在student类:

<aop:config>
  <aop:aspect id="myaspect" ref="abean">

  <aop:pointcut id="businessservice"
   expression="execution(* com.yiibai.student.getname(..))"/>
  ...
  </aop:aspect>
</aop:config>

<bean id="abean" class="...">
...
</bean>

声明建议
可以声明任意五个建议的使用<aop:{advice name}>元素下面给出一个<aop:aspect>内:

<aop:config>
  <aop:aspect id="myaspect" ref="abean">
   <aop:pointcut id="businessservice"
     expression="execution(* com.xyz.myapp.service.*.*(..))"/>

   <!-- a before advice definition -->
   <aop:before pointcut-ref="businessservice" 
     method="dorequiredtask"/>

   <!-- an after advice definition -->
   <aop:after pointcut-ref="businessservice" 
     method="dorequiredtask"/>

   <!-- an after-returning advice definition -->
   <!--the dorequiredtask method must have parameter named retval -->
   <aop:after-returning pointcut-ref="businessservice"
     returning="retval"
     method="dorequiredtask"/>

   <!-- an after-throwing advice definition -->
   <!--the dorequiredtask method must have parameter named ex -->
   <aop:after-throwing pointcut-ref="businessservice"
     throwing="ex"
     method="dorequiredtask"/>

   <!-- an around advice definition -->
   <aop:around pointcut-ref="businessservice" 
     method="dorequiredtask"/>
  ...
  </aop:aspect>
</aop:config>

<bean id="abean" class="...">
...
</bean>

可以使用相同的dorequiredtask或不同的方法针对不同的建议。这些方法将被定义为纵横模块的一部分。

基于xml模式的aop例
要理解上述关系到xml模式的aop提到的概念,让我们写这将实现几个建议的一个例子。

这里是logging.java文件的内容。这实际上是纵横模块的一个示例,它定义的方法被调用的各个点。

package com.yiibai;

public class logging {

  /** 
  * this is the method which i would like to execute
  * before a selected method execution.
  */
  public void beforeadvice(){
   system.out.println("going to setup student profile.");
  }

  /** 
  * this is the method which i would like to execute
  * after a selected method execution.
  */
  public void afteradvice(){
   system.out.println("student profile has been setup.");
  }

  /** 
  * this is the method which i would like to execute
  * when any method returns.
  */
  public void afterreturningadvice(object retval){
   system.out.println("returning:" + retval.tostring() );
  }

  /**
  * this is the method which i would like to execute
  * if there is an exception raised.
  */
  public void afterthrowingadvice(illegalargumentexception ex){
   system.out.println("there has been an exception: " + ex.tostring());  
  }
  
}

以下是student.java文件的内容:

package com.yiibai;

public class student {
  private integer age;
  private string name;

  public void setage(integer age) {
   this.age = age;
  }
  public integer getage() {
  system.out.println("age : " + age );
   return age;
  }

  public void setname(string name) {
   this.name = name;
  }
  public string getname() {
   system.out.println("name : " + name );
   return name;
  }
  
  public void printthrowexception(){
  system.out.println("exception raised");
    throw new illegalargumentexception();
  }
}

以下是mainapp.java文件的内容:

package com.yiibai;

import org.springframework.context.applicationcontext;
import org.springframework.context.support.classpathxmlapplicationcontext;

public class mainapp {
  public static void main(string[] args) {
   applicationcontext context = 
       new classpathxmlapplicationcontext("beans.xml");

   student student = (student) context.getbean("student");

   student.getname();
   student.getage();
   
   student.printthrowexception();
  }
}

以下是配置文件beans.xml文件:

<?xml version="1.0" encoding="utf-8"?>
<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"
  xsi:schemalocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
  http://www.springframework.org/schema/aop 
  http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

  <aop:config>
   <aop:aspect id="log" ref="logging">
     <aop:pointcut id="selectall" 
     expression="execution(* com.yiibai.*.*(..))"/>
     <aop:before pointcut-ref="selectall" method="beforeadvice"/>
     <aop:after pointcut-ref="selectall" method="afteradvice"/>
     <aop:after-returning pointcut-ref="selectall" 
               returning="retval"
               method="afterreturningadvice"/>
     <aop:after-throwing pointcut-ref="selectall" 
               throwing="ex"
               method="afterthrowingadvice"/>
   </aop:aspect>
  </aop:config>

  <!-- definition for student bean -->
  <bean id="student" class="com.yiibai.student">
   <property name="name" value="zara" />
   <property name="age" value="11"/>   
  </bean>

  <!-- definition for logging aspect -->
  <bean id="logging" class="com.yiibai.logging"/> 
   
</beans>

创建源代码和bean配置文件完成后,让我们运行应用程序。如果一切顺利,这将打印以下信息:

going to setup student profile.
name : zara
student profile has been setup.
returning:zara
going to setup student profile.
age : 11
student profile has been setup.
returning:11
going to setup student profile.
exception raised
student profile has been setup.
there has been an exception: java.lang.illegalargumentexception
.....
other exception content

解释一下,上面定义<aop:pointcut>选择所有的包com.yiibai下定义的方法。让我们假设,想有一个特定的方法之前或之后执行意见,可以定义切入点与实际的类和方法的名称取代星号(*)的切入点定义来缩小执行。下面是修改后的xml配置文件,以显示概念:

<?xml version="1.0" encoding="utf-8"?>
<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"
  xsi:schemalocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
  http://www.springframework.org/schema/aop 
  http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

  <aop:config>
  <aop:aspect id="log" ref="logging">
   <aop:pointcut id="selectall" 
   expression="execution(* com.yiibai.student.getname(..))"/>
   <aop:before pointcut-ref="selectall" method="beforeadvice"/>
   <aop:after pointcut-ref="selectall" method="afteradvice"/>
  </aop:aspect>
  </aop:config>

  <!-- definition for student bean -->
  <bean id="student" class="com.yiibai.student">
   <property name="name" value="zara" />
   <property name="age" value="11"/>   
  </bean>

  <!-- definition for logging aspect -->
  <bean id="logging" class="com.yiibai.logging"/> 
   
</beans>

如果执行这些配置更改的示例应用程序,这将打印以下信息:

going to setup student profile.
name : zara
student profile has been setup.
age : 11
exception raised
.....
other exception content

基于@aspectj的aop
@ aspectj是指声明方面的风格注释的使用java 5注释普通的java类。对@ aspectj支持由包括您基于xml schema的配置文件里面的下列元素启用。

<aop:aspectj-autoproxy/>

您还需要在以下应用程序的类路径中的aspectj库。这些库可以在aspectj的安装的'lib'目录,可以从网上下载他们.

  • aspectjrt.jar
  • aspectjweaver.jar
  • aspectj.jar

声明一个切面
方面类是像任何其他普通的bean,并可能有方法和字段,就像任何其他类,但他们将被标注了@aspect 如下:

package org.xyz;

import org.aspectj.lang.annotation.aspect;

@aspect
public class aspectmodule {

}

他们将在xml中进行配置像任何其他的bean,如下所示:

<bean id="myaspect" class="org.xyz.aspectmodule">
  <!-- configure properties of aspect here as normal -->
</bean>

声明一个切入点
一个切入点有助于确定与不同意见要执行的连接点的权益(即方法)。同时用@aspectj的基础配置工作,切入点声明有两个部分:

切入点表达式,决定哪些方法执行我们感兴趣

一个切入点签名的包含名字和任意数量的参数。该方法的实际主体是不相关的,实际上应为空。

下面的示例定义一个名为'businessservice“切入点将匹配每个方法的可用包com.xyz.myapp.service下执行中的类:

import org.aspectj.lang.annotation.pointcut;

@pointcut("execution(* com.xyz.myapp.service.*.*(..))") // expression 
private void businessservice() {} // signature

下面的示例定义一个名为'getname'切入点将匹配可用的软件包com.yiibai下执行getname()方法在student类:

import org.aspectj.lang.annotation.pointcut;

@pointcut("execution(* com.yiibai.student.getname(..))") 
private void getname() {}

声明建议
可以声明任何使用 @{advice-name} 注释下面给出的五个建议。这假定已经定义了一个切入点签名的方法的businessservice():

@before("businessservice()")
public void dobeforetask(){
 ...
}

@after("businessservice()")
public void doaftertask(){
 ...
}

@afterreturning(pointcut = "businessservice()", returning="retval")
public void doafterreturnningtask(object retval){
 // you can intercept retval here.
 ...
}

@afterthrowing(pointcut = "businessservice()", throwing="ex")
public void doafterthrowingtask(exception ex){
 // you can intercept thrown exception here.
 ...
}

@around("businessservice()")
public void doaroundtask(){
 ...
}

可以定义内置切入点的任何意见的。下面是一个例子定义内联的切入点之前的建议:

@before("execution(* com.xyz.myapp.service.*.*(..))")
public dobeforetask(){
 ...
}
@aspectj 基于aop例子
要理解上述关系到@aspectj的aop的基础概念提到,让我们写这将实现几个建议的一个例子。

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

package com.yiibai;

import org.aspectj.lang.annotation.aspect;
import org.aspectj.lang.annotation.pointcut;
import org.aspectj.lang.annotation.before;
import org.aspectj.lang.annotation.after;
import org.aspectj.lang.annotation.afterthrowing;
import org.aspectj.lang.annotation.afterreturning;
import org.aspectj.lang.annotation.around;

@aspect
public class logging {

  /** following is the definition for a pointcut to select
  * all the methods available. so advice will be called
  * for all the methods.
  */
  @pointcut("execution(* com.yiibai.*.*(..))")
  private void selectall(){}

  /** 
  * this is the method which i would like to execute
  * before a selected method execution.
  */
  @before("selectall()")
  public void beforeadvice(){
   system.out.println("going to setup student profile.");
  }

  /** 
  * this is the method which i would like to execute
  * after a selected method execution.
  */
  @after("selectall()")
  public void afteradvice(){
   system.out.println("student profile has been setup.");
  }

  /** 
  * this is the method which i would like to execute
  * when any method returns.
  */
  @afterreturning(pointcut = "selectall()", returning="retval")
  public void afterreturningadvice(object retval){
   system.out.println("returning:" + retval.tostring() );
  }

  /**
  * this is the method which i would like to execute
  * if there is an exception raised by any method.
  */
  @afterthrowing(pointcut = "selectall()", throwing = "ex")
  public void afterthrowingadvice(illegalargumentexception ex){
   system.out.println("there has been an exception: " + ex.tostring());  
  }
  
}

以下是student.java文件的内容:

package com.yiibai;

public class student {
  private integer age;
  private string name;

  public void setage(integer age) {
   this.age = age;
  }
  public integer getage() {
  system.out.println("age : " + age );
   return age;
  }

  public void setname(string name) {
   this.name = name;
  }
  public string getname() {
   system.out.println("name : " + name );
   return name;
  }
  public void printthrowexception(){
   system.out.println("exception raised");
   throw new illegalargumentexception();
  }
}

以下是mainapp.java文件的内容:

package com.yiibai;

import org.springframework.context.applicationcontext;
import org.springframework.context.support.classpathxmlapplicationcontext;

public class mainapp {
  public static void main(string[] args) {
   applicationcontext context = 
       new classpathxmlapplicationcontext("beans.xml");

   student student = (student) context.getbean("student");

   student.getname();
   student.getage();
   
   student.printthrowexception();
  }
}

以下是配置文件beans.xml文件:

<?xml version="1.0" encoding="utf-8"?>
<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"
  xsi:schemalocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
  http://www.springframework.org/schema/aop 
  http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

  <aop:aspectj-autoproxy/>

  <!-- definition for student bean -->
  <bean id="student" class="com.yiibai.student">
   <property name="name" value="zara" />
   <property name="age" value="11"/>   
  </bean>

  <!-- definition for logging aspect -->
  <bean id="logging" class="com.yiibai.logging"/> 
   
</beans>

创建源程序和bean配置文件完成后,让我们运行应用程序。如果一切顺利,这将打印以下信息:

going to setup student profile.
name : zara
student profile has been setup.
returning:zara
going to setup student profile.
age : 11
student profile has been setup.
returning:11
going to setup student profile.
exception raised
student profile has been setup.
there has been an exception: java.lang.illegalargumentexception
.....
other exception content