您的位置:首页 > 编程语言 > Java开发

Spring中基于Schema的AOP配置详解

2016-04-22 14:22 756 查看
应用中进行AOP的编程开发,通过Spring框架可以有两种选择:
利用 Spring AOP
利用 AspectJ(此处略)

利用Spring AOP进行AOP的编程开发,定义AOP相关实现有两种方式:
基于XML Schema的配置文件定义
通过@Aspect系列标注定义

下面我们详细介绍如何通过大家熟悉的XML配置文件进行AOP开发。

1.首先在XML配置文件中,引入AOP的XSD
<?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.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
...
</beans>注意其中的xmlns:aop

2.在XML配置文件在,所有与AOP相关的配置必须置于<aop:config>范围内
不过,在一个XML配置文件中可以有多个<aop:config>。

3.<aop:aspect>声明一个aspect
aspect就是一个普通的Java类。
<aop:config>
<aop:aspect id="myAspect" ref="aBean">
...
</aop:aspect>
</aop:config>

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

4.<aop:pointcut>声明一个pointcut
pointcut就是符合插入aspect的条件的包名或类名。运行时,执行到此处,会插入关联的aspect。
<aop:config>

<aop:pointcut id="businessService"
expression="com.jdsu.nc.portal.SystemArchitecture.businessService()"/>

</aop:config>

<aop:pointcut>可以作为<aop:config>的直接子元素,声明通用的顶级pointcut,如上所示;也可以作为<aop:aspect>的子元素,为一个确切的aspect声明专用的pointcut。
<aop:config>

<aop:aspect id="myAspect" ref="aBean">

<aop:pointcut id="businessService"
expression="execution(* com.jdsu.nc.portal.service.*.*(..))"/>

...

</aop:aspect>

</aop:config>

5.为一个aspect声明advice
一个aspect可以声明多个advice。声明advice的时候,必须给出pointcut和被插入执行的method。

Spring AOP支持5种advice,包括<aop:before>、<aop:after>、<aop:after-returning>、<aop:after-throwing>、<aop:around>。当其他advice都不合适的情况下,才使用<aop:around>。下面以<aop:before>为例。
<aop:aspect id="myAspect" ref="aBean">

<aop:before
pointcut-ref="businessService"
method="doAccessCheck"/>

...

</aop:aspect>

6.<aop:declare-parents>声明introduction
<aop:aspect id="usageTrackerAspect" ref="usageTracking">

<aop:declare-parents
types-matching="com.jdsu.nc.portal.service.*+"
implement-interface="com.jdsu.nc.portal.service.tracking.UsageTracked"
default-impl="com.jdsu.nc.portal.service.tracking.DefaultUsageTracked"/>

</aop:aspect>

7.<aop:advisor>
advisor是Spring AOP所特有的概念,实际上advisor可以被看作是一个缩微的aspect,所以advisor不属于任何aspect。
一个advisor中只定义一个advice及关联的pointcut。
对于使用<tx:advice>定义的独立的advice,可以通过<aop:advisor>被关联到插入点,示例如下:
<aop:config>

<aop:pointcut id="businessService"
expression="execution(* com.jdsu.nc.portal.service.*.*(..))"/>

<aop:advisor
pointcut-ref="businessService"
advice-ref="tx-advice"/>

</aop:config>

<tx:advice id="tx-advice">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring aop schema Aspect