使用Spring进行切面(AOP)编程


一、   AOP理论

AOP为Aspect Oriented Programming的缩写,意为:面向切面编程(也叫面向方面),可以通过预编译方式和运行期动态代理实现在不修改源代码的情况下给程序动态统一添加功能的一种技术。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

u  横切性关注点

对哪些方法进行拦截,拦截该方法后怎么处理,这些关注就称之为横切面关注点。

u  Aspect(切面)

指横切性的关注点的抽象即为切面,它与类相似,只是两者的关注点不一样,类是对物体特征的抽象,而切面是对横切性关注点的抽象。

u  Joinpoint(连接点)

所谓连接点就是那些被拦截的点(也就是需要被拦截的类的方法)。在Spring中,这些点指的只能是方法,因为Spring只支持方法类型的拦截,实际上Joinpoint还可以拦截field或类构造器。

u  Pointcut(切入点)

所谓切入点是指那些我们对Jointpoint(连接点)进行拦截的定义,也就是在切面中定义的方法,并声明该方法拦截了Jointpoint(连接点)。

u  Advice(通知)

所谓通知就是指切入点拦截到Jointpoint(连接点)之后要做的事情。通知分为前置通知(@Before)、后置通知(@AfterReturning)、异常通知(@AfterThrowing)、最终通知(@After)和环绕通知(@Around)。

u  Target(目标对象)

代理的目标对象。

u  Weave(织入)

指将aspects应用到target对象并导致proxy对象创建的过程称为织入。

u  Introduction(引入)

在不修改类代码的前提下,introduction可以在运行期为类动态的添加一些方法或Field(字段)。

二、   AOP编程的方式

要使用AOP进行编程,我们需要在Spring的配置文件(比如名为applicationContext.xml)中先引入AOP的命名空间,配置文件的引入内容如下面红色字体:

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

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

 xmlns:context="http://www.springframework.org/schema/context"

    xmlns:aop="http://www.springframework.org/schema/aop"     xsi:schemaLocation="http://www.springframework.org/schema/beans            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd

http://www.springframework.org/schema/context           http://www.springframework.org/schema/context/spring-context-2.5.xsd

http://www.springframework.org/schema/aop           http://www.springframework.org/schema/aop/spring-aop-2.5.xsd ">

Spring的提供了两种AOP编程方式,我们可以选择其中的任何一种来进行AOP编程。

1.         基于注解方式的AOP编程

2.         基于XML配置方式的AOP编程

三、   实例演示AOP编程

这里通过演示AspectBean切面来拦截StudentMgr的update方法(连接点)来描述切面编程具体是如何工作的。先以注解的方式来说明,后面会给出相应的xml配置信息。

1.         搭建AOP编程环境

AOP环境的搭建参考文章 利用Maven搭建Spring开发环境 见 。

2.         开启注解方式

在Spring的配置文件中增加下面的一个bean以开启Spring的注解编程

<bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator" />

 

3.         定义IstudentMgr接口及bean类StudentMgr,代码如下

IstudentMgr接口Java代码:

[java]
  1. package com.trs.components.mgr;  
  2.   
  3.  public interface IStudentMgr {  
  4.   
  5.     public void save(String _sStudentName) throws Exception;  
  6.   
  7.     public void update(String _sStudentName) throws Exception;  
  8.   
  9. }  
  10.    


StudentMgr的bean类java代码:

[java]
  1. package com.trs.components.mgr;  
  2.   
  3.  public class StudentMgr implements IStudentMgr {  
  4.   
  5.     public void save(String _sStudentName) throws Exception {  
  6.   
  7.         System.out.println("保存了学生对象..");  
  8.   
  9.     }  
  10.   
  11.     public void update(String _sStudentName)throws Exception{  
  12.   
  13.         System.out.println("更新了学生对象..");  
  14.   
  15.     }  
  16.   
  17. }   
  • 1
  • 2
  • 3
  • 下一页

相关内容