转载

Spring框架的AOP

   

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

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

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

AOP术语:

在我们开始使用AOP之前,先熟悉AOP的概念和术语。这些条款是不特定于Spring,问题都是有关AOP。

术语 描述
Aspect A module which has a set of APIs providing cross-cutting requirements. For example, a logging module would be called AOP aspect for logging. An application can have any number of aspects depending on the requirement.
Join point This represents a point in your application where you can plug-in AOP aspect. You can also say, it is the actual place in the application where an action will be taken using Spring AOP framework.
Advice This is the actual action to be taken either before or after the method execution. This is actual piece of code that is invoked during program execution by Spring AOP framework.
Pointcut This is a set of one or more joinpoints where an advice should be executed. You can specify pointcuts using expressions or patterns as we will see in our AOP examples.
Introduction An introduction allows you to add new methods or attributes to existing classes.
Target object The object being advised by one or more aspects, this object will always be a proxied object. Also referred to as the advised object.
Weaving Weaving is the process of linking aspects with other application types or objects to create an advised object. This can be done at compile time, load time, or at runtime.

建议的类型

Spring方面可以用5种下面提到的建议:

Advice 描述
before 在一个方法执行之前运行的建议。
after 该方法的执行,无论其结果如何运行后建议。
after-returning 只有当方法成功地完成了一个方法执行后运行的建议。
after-throwing 在一个方法执行后运行建议只有当方法因抛出一个异常。
around 建议的方法之前和之后运行建议被调用。

自定义方面实现

Spring支持@AspectJ注解风格的方法,并实现自定义方面的架构为基础的方法。这两种方法已被详细地在下面的两个子章节解释

方法 描述
基于XML Schema 切面可以使用类以及基于XML的配置来实现。
基于@AspectJ @ AspectJ是指声明方面的风格注释的使用Java 5注释普通的Java类。

   
正文到此结束
Loading...