码迷,mamicode.com
首页 > 编程语言 > 详细

Spring AOP 在XML中声明切面

时间:2017-06-16 10:26:00      阅读:297      评论:0      收藏:0      [点我收藏+]

标签:add   tom   iso   oid   配置   config   而且   bug   man   

 

转载地址:http://www.jianshu.com/p/43a0bc21805f

XML中将一个Java类配置成一个切面:

AOP元素

用途

<aop:advisor>

定义AOP通知器

<aop:after>

定义一个后置通知(不管目标方法是否执行成功)

<aop:after-returning>

定义AOP返回通知

<aop:after-throwing>

定义AOP异常通知

<aop:around>

定义环绕通知

<aop:aspect>

定义一个切面

<aop:aspectj-autoproxy>

启动@AspectJ注解驱动的切面

<aop:before>

定义一个AOP前置通知

<aop:config>

顶层AOP配置元素。大多数的<aop:*>元素都必须包含在<aop:config>元素内

<aop:declare-parents>

以透明的方式为被通知的对象引入额外的接口

<aop:pointcut>

定义一个切点

  我们之前已经看过了<aop:adpectj-autoproxy>元素,他能够自动代理AspectJ注解的通知类。aop的其他元素可以让我们直接在XML中配置切面,而不使用注解,下面我们定义一个不使用任何注解的Audience类:

package com.spring.aop.service.aop;

 

/**

* <dl>

* <dd>Description:观看演出的切面</dd>

* <dd>Company: 黑科技</dd>

* <dd>@date201693 下午9:58:09</dd>

* <dd>@authorKong</dd>

* </dl>

*/

@Aspect

public class Audience {

 

/**

* 目标方法执行之前调用

*/

public void silenceCellPhone() {

System.out.println("Silencing cell phones");

}

 

/**

* 目标方法执行之前调用

*/

public void takeSeats() {

System.out.println("Taking seats");

}

 

/**

* 目标方法执行完后调用

*/

public void applause() {

System.out.println("CLAP CLAP CLAP");

}

 

/**

* 目标方法发生异常时调用

*/

public void demandRefund() {

System.out.println("Demanding a refund");

}

 

}

  现在看来Audience类和普通的Java类没有任何的区别,但是我们只需要在Xml中稍作配置,他就可以成为一个切面。

1.声明前置和后置通知

<aop:config>

<aop:aspect ref="audience">

 

<aop:before pointcut="execution(** com.spring.aop.service.Perfomance.perform(..)"

method="silenceCellPhone"/>

 

<aop:before pointcut="execution(** com.spring.aop.service.Perfomance.perform(..)"

method="takeSeats"/>

 

<aop:after-returning pointcut="execution(** com.spring.aop.service.Perfomance.perform(..)"

method="applause"/>

 

<aop:after-throwing pointcut="execution(** com.spring.aop.service.Perfomance.perform(..)"

method="demandRefund"/>

</aop:aspect>

</aop:config>

  聪明的小伙伴一定又发现了,相同的切点我们写了四次,这是不科学的,强大的Spring不会允许有这样的Bug出现,你猜对了,可以使用<aop:pointcut>元素定义一个公共的切点,而且这个切点还可以定义在切面类的外边,供其他的切面使用:

<aop:config>

 

<aop:pointcut id="performance"

expression="execution(** com.spring.aop.service.Perfomance.perform(..)" />

 

<aop:aspect ref="audience">

 

<aop:before pointcut-ref="performance" method="silenceCellPhone"/>

 

<aop:before pointcut-ref="performance" method="takeSeats"/>

 

<aop:after-returning pointcut-ref="performance" method="applause"/>

 

<aop:after-throwing pointcut-ref="performance"method="demandRefund"/>

</aop:aspect>

</aop:config>

2.Xml中配置环绕通知

3.为通知传递参数

4.通过切面引入新方法

Spring AOP 在XML中声明切面

标签:add   tom   iso   oid   配置   config   而且   bug   man   

原文地址:http://www.cnblogs.com/xiaolang8762400/p/7022262.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!