一、

假设有如下情况,有一个演凑者和一批观众,要实现在演凑者的演凑方法前织入观众的"坐下"、"关手机方法",在演凑结束后,如果成功,则织入观众"鼓掌",演凑出错则观众要求"回水"

基本的类如下:

1.

package com.springinaction.springidol;

public interface Instrument {
public void play();
}

2.

 package com.springinaction.springidol;

 public class Guitar implements Instrument {
public void play() {
System.out.println("Strum strum strum");
}
}

3.

package com.springinaction.springidol;

public interface Performer {
void perform() throws PerformanceException;
}

4.

 package com.springinaction.springidol;

 public class Instrumentalist implements Performer {
public void perform() throws PerformanceException {
instrument.play();
} private Instrument instrument; public void setInstrument(Instrument instrument) {
this.instrument = instrument;
} public Instrument getInstrument() {
return instrument;
}
}

二、

可以定义的advice

Spring的切面是一个pojo

1.使用@Aspect定义切面类

(1)不同的方法可以用不同的pointcut

 package concert;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
public class Audience {
@Before("execution(** concert.Performance.perform(..))")
public void silenceCellPhones() {
System.out.println("Silencing cell phones");
}
@Before("execution(** concert.Performance.perform(..))")
public void takeSeats() {
System.out.println("Taking seats");
}
@AfterReturning("execution(** concert.Performance.perform(..))")
public void applause() {
System.out.println("CLAP CLAP CLAP!!!");
}
@AfterThrowing("execution(** concert.Performance.perform(..))")
public void demandRefund() {
System.out.println("Demanding a refund");
}
}

(2)定义一个公共的pointcut,其对应的方法名就是id

 package com.springinaction.springidol;

 import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut; @Aspect
public class Audience {
@Pointcut(
"execution(* com.springinaction.springidol.Performer.perform(..))")
public void performance() { //<co id="co_definePointcut"/>
} @Before("performance()")
public void takeSeats() { //<co id="co_takeSeatsBefore"/>
System.out.println("The audience is taking their seats.");
} @Before("performance()")
public void turnOffCellPhones() { //<co id="co_turnOffCellPhonesBefore"/>
System.out.println("The audience is turning off their cellphones");
} @AfterReturning("performance()")
public void applaud() { //<co id="co_applaudAfter"/>
System.out.println("CLAP CLAP CLAP CLAP CLAP");
} @AfterThrowing("performance()")
public void demandRefund() { //<co id="co_demandRefundAfterException"/>
System.out.println("Boo! We want our money back!");
}
}

2.把切面交给Spring容器

(1)在java配置文件中,使用@EnableAspectJAutoProxy

 package concert;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration
@EnableAspectJAutoProxy
@ComponentScan
public class ConcertConfig {
@Bean
public Audience audience() {
return new Audience();
}
}

(2)在xml使用<aop:aspectj-autoproxy>

 <?xml version="1.0" encoding="UTF-8"?>
<!--<start id="preamble" />-->
<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">
<!--<end id="preamble" />--> <bean id="eddie"
class="com.springinaction.springidol.Instrumentalist">
<property name="instrument">
<bean class="com.springinaction.springidol.Guitar" />
</property>
</bean> <!--<start id="audience_bean" />-->
<bean id="audience"
class="com.springinaction.springidol.Audience" />
<!--<end id="audience_bean" />--> <!--<start id="contestant_introducer" />-->
<bean class="com.springinaction.springidol.ContestantIntroducer" />
<!--<end id="contestant_introducer" />--> <!--<start id="aspectj_autoproxy" />-->
<aop:aspectj-autoproxy />
<!--<end id="aspectj_autoproxy" />--> </beans>

3.测试

package com.springinaction.springidol;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("spring-idol.xml")
public class AspectTest {
@Autowired
ApplicationContext context; @Test
public void audienceShouldApplaud() throws Exception {
Performer eddie = (Performer) context.getBean("eddie");
eddie.perform();
} @Test
public void eddieShouldBeAContestant() {
Contestant eddie = (Contestant) context.getBean("eddie");
eddie.receiveAward();
}
}

audienceShouldApplaud的测试结果:

The audience is taking their seats.
The audience is turning off their cellphones
Strum strum strum
CLAP CLAP CLAP CLAP CLAP

SPRING IN ACTION 第4版笔记-第四章ASPECT-ORIENTED SPRING-005-定义切面使用@Aspect、@EnableAspectJAutoProxy、<aop:aspectj-autoproxy>的更多相关文章

  1. SPRING IN ACTION 第4版笔记-第四章ASPECT-ORIENTED SPRING-010-Introduction为类增加新方法@DeclareParents、<aop:declare-parents>

    一. 1.Introduction的作用是给类动态的增加方法 When Spring discovers a bean annotated with @Aspect , it will automat ...

  2. SPRING IN ACTION 第4版笔记-第四章ASPECT-ORIENTED SPRING-003-Spring对AOP支持情况的介绍

    一. 不同的Aop框架在支持aspect何时.如何织入到目标中是不一样的.如AspectJ和Jboss支持在构造函数和field被修改时织入,但spring不支持,spring只支持一般method的 ...

  3. SPRING IN ACTION 第4版笔记-第四章ASPECT-ORIENTED SPRING-004-使用AspectJ’s pointcut expression language定义Pointcut

    一. 1.在Spring中,pointcut是通过AspectJ’s pointcut expression language来定义的,但spring只支持它的一部分,如果超出范围就会报Illegal ...

  4. SPRING IN ACTION 第4版笔记-第四章ASPECT-ORIENTED SPRING-002-AOP术语解析

    一. 1.Advice Advice是切面的要做的操作,它定义了what.when(什么时候要做什么事) aspects have a purpose—a job they’re meant to d ...

  5. SPRING IN ACTION 第4版笔记-第四章ASPECT-ORIENTED SPRING-012-AOP总结

    1.AOP是面向对象编程的有力补充,它可以让你把分散在应用中的公共辅助功能抽取成模块,以灵活配置,减少了重复代码,让类更关注于自身的功能

  6. SPRING IN ACTION 第4版笔记-第四章ASPECT-ORIENTED SPRING-011-注入AspectJ Aspect

    一. 1. package concert; public interface CriticismEngine { public String getCriticism(); } 2. package ...

  7. SPRING IN ACTION 第4版笔记-第四章ASPECT-ORIENTED SPRING-009-带参数的ADVICE2 配置文件为XML

    一. 1.配置文件为xml时则切面类不用写aop的anotation package com.springinaction.springidol; public class Magician impl ...

  8. SPRING IN ACTION 第4版笔记-第四章ASPECT-ORIENTED SPRING-009-带参数的ADVICE2

    一. 情景:有个魔术师会读心术,常人一想一事物他就能读到.以魔术师为切面织入常人的内心. 二. 1. // <start id="mindreader_java" /> ...

  9. SPRING IN ACTION 第4版笔记-第四章ASPECT-ORIENTED SPRING-008-带参数的ADVICE

    一. 假设有情形如:cd里有很多轨,当播放音乐时,要统计每个音轨的播放次数,这些统计操作不应放在播放方法里,因为统计不是播放音乐的主要职责,这种情况适合应用AOP. 二. 1. package sou ...

随机推荐

  1. 在不同版本的 IIS 上使用 ASP.NET MVC

    ASP.NET MVC Framework 依赖于 URL 路由.为了利用 URL 路由,可能不得不在 Web 服务器上执行额外的配置步骤.这些步骤取决于 Internet Information S ...

  2. Eclipse Memory Analysis进行堆转储文件分析

    生成堆转储文件 新建项目,设置Eclispe Java堆的大小: (1)限制Java堆大小:将最小值 -Xms参数与最大值-Xmx参数设置一样可避免堆的扩展         -Xmx20m -Xms2 ...

  3. java Springmvc ajax上传

    ajax上传方式相对于普通的form上传方式要便捷,在更多的时候都会使用ajax (简单的小示例) 1.要先去下载一个 jquery.ajaxfileupload.js(基于jquery.js上的js ...

  4. InstallShield Clone dialog

    Browse to Dialogs view, right-click an existing dialog, click Clone and rename the cloned dialog. Wh ...

  5. IOPS和Throughput

    IOPS和Throughput吞吐量两个参数是衡量存储性能的主要指标.IOPS表示存储每秒传输IO的数量,Throughput吞吐量则表示每秒数据的传输总量.两者在不同的情况下都能表示存储的性能状况, ...

  6. 阿里云 CentOS 安装JDK

    初用阿里云,使用centOS linux64操作系统 . 自己上传jdk文件总是安装失败,原因估计是因为我的网络不好,导致文件损坏. 解决办法,直接在linux命令行模式下,到官网下载 jdk,命令如 ...

  7. A Case Study -- Performance Evaluation of a DRAM-Based Solid State Disk

    研究将固态硬盘作为持久存储层和传统硬盘的在数据库性能上的研究

  8. think完全还原原形的 SQL

    $dd     =   Db::getInstance(); //实例连接数据库$sql = "SELECT * FROM `yezi_friendlinks`"; // SQL$ ...

  9. rman全备份异机恢复

    一.测试环境 [oracle@localhost ~]$ uname -a Linux localhost.localdomain -.el6.x86_64 # SMP Tue May :: EDT ...

  10. WinForm小小应用

    制作日历计划任务 private void BeginTask() { Thread th = new Thread(//建立线程 (() =>//使用Lambda表达式 { while (tr ...