一、

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

二、

1.

package soundsystem;

public interface CompactDisc {

  void play();
void playTrack(int trackNumber);
}

2.

 package soundsystem;

 import java.util.List;

 public class BlankDisc implements CompactDisc {

     private String title;
private String artist;
private List<String> tracks; public BlankDisc() {
super();
} public BlankDisc(String title, String artist, List<String> tracks) {
this.title = title;
this.artist = artist;
this.tracks = tracks;
} public void play() {
System.out.println("Playing " + title + " by " + artist);
for (String track : tracks) {
System.out.println("-Track: " + track);
}
} public String getTitle() {
return title;
} public void setTitle(String title) {
this.title = title;
} public String getArtist() {
return artist;
} public void setArtist(String artist) {
this.artist = artist;
} public List<String> getTracks() {
return tracks;
} public void setTracks(List<String> tracks) {
this.tracks = tracks;
} @Override
public void playTrack(int trackNumber) {
System.out.println("playTrack---->" + trackNumber);
} }

3.

 package soundsystem;

 import java.util.HashMap;
import java.util.Map;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut; @Aspect
public class TrackCounter {
private Map<Integer, Integer> trackCounts = new HashMap<Integer, Integer>(); @Pointcut("execution(* soundsystem.CompactDisc.playTrack(int)) "
+ "&& args(trackNumber)")
public void trackPlayed(int trackNumber) {
} @Before("trackPlayed(trackNumber)")
public void countTrack(int trackNumber) {
int currentCount = getPlayCount(trackNumber);
trackCounts.put(trackNumber, currentCount + 1);
} public int getPlayCount(int trackNumber) {
return trackCounts.containsKey(trackNumber) ? trackCounts
.get(trackNumber) : 0;
}
}

The thing to focus on in the figure is the args(trackNumber) qualifier in the pointcut expression. This indicates that any int argument that is passed into the execution of playTrack() should also be passed into the advice. The parameter name,trackNumber , also matches the parameter in the pointcut method signature.

4.配置文件

 package soundsystem;

 import java.util.ArrayList;
import java.util.List; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy; @Configuration
@EnableAspectJAutoProxy
public class TrackCounterConfig {
@Bean
public CompactDisc cd() {
BlankDisc cd = new BlankDisc();
cd.setTitle("Sgt. Pepper's Lonely Hearts Club Band");
cd.setArtist("The Beatles");
List<String> tracks = new ArrayList<String>();
tracks.add("Sgt. Pepper's Lonely Hearts Club Band");
tracks.add("With a Little Help from My Friends");
tracks.add("Lucy in the Sky with Diamonds");
tracks.add("Getting Better");
tracks.add("Fixing a Hole");
// ...other tracks omitted for brevity...
cd.setTracks(tracks);
return cd;
} @Bean
public TrackCounter trackCounter() {
return new TrackCounter();
}
}

5.或xml作配置文件

 <?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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="trackCounter" class="soundsystem.TrackCounter" />
<bean id="cd" class="soundsystem.BlankDisc">
<property name="title" value="Sgt. Pepper's Lonely Hearts Club Band" />
<property name="artist" value="The Beatles" />
<property name="tracks">
<list>
<value>Sgt. Pepper's Lonely Hearts Club Band</value>
<value>With a Little Help from My Friends</value>
<value>Lucy in the Sky with Diamonds</value>
<value>Getting Better</value>
<value>Fixing a Hole</value>
<!-- ...other tracks omitted for brevity... -->
</list>
</property>
</bean>
<aop:config>
<aop:aspect ref="trackCounter">
<aop:pointcut id="trackPlayed" expression="execution(* soundsystem.CompactDisc.playTrack(int))
and args(trackNumber)" />
<aop:before pointcut-ref="trackPlayed" method="countTrack" />
</aop:aspect>
</aop:config>
</beans>

6.测试

 package soundsystem;

 import static org.junit.Assert.assertEquals;

 import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.StandardOutputStreamLog;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TrackCounterConfig.class)
public class TrackCounterTest {
@Rule
public final StandardOutputStreamLog log = new StandardOutputStreamLog();
@Autowired
private CompactDisc cd;
@Autowired
private TrackCounter counter; @Test
public void testTrackCounter() {
cd.playTrack(1);
cd.playTrack(2);
cd.playTrack(3);
cd.playTrack(3);
cd.playTrack(3);
cd.playTrack(3);
cd.playTrack(7);
cd.playTrack(7);
assertEquals(1, counter.getPlayCount(1));
assertEquals(1, counter.getPlayCount(2));
assertEquals(4, counter.getPlayCount(3));
assertEquals(0, counter.getPlayCount(4));
assertEquals(0, counter.getPlayCount(5));
assertEquals(0, counter.getPlayCount(6));
assertEquals(2, counter.getPlayCount(7));
}
}

SPRING IN ACTION 第4版笔记-第四章ASPECT-ORIENTED SPRING-008-带参数的ADVICE的更多相关文章

  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-005-定义切面使用@Aspect、@EnableAspectJAutoProxy、<aop:aspectj-autoproxy>

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

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

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

  5. 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 ...

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

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

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

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

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

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

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

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

随机推荐

  1. Ajax的Get和Post的区别

    Ajax的Get和Post的区别Get方式:用get方式可传送简单数据,但大小一般限制在1KB下,数据追加到url中发送(http的header传送),也就是说,浏览器将各个表单字段元素及其数据按照U ...

  2. ###《Video Event Detection by Inferring Temporal Instance Lables》

    论文作者:Kuan-Ting Lai, Felix X. Yu, Ming-Syan Chen and Shih-Fu Chang. #@author: gr #@date: 2014-01-25 # ...

  3. __nonnull 和 __nullable (Swift 和 Objective-C混编)

    苹果在 Xcode 6.3 以后,为了解决 Swift 与 OC 混编时的问题,引入了一个 Objective-C 的新特性:nullability annotations. 这一新特性的核心是两个新 ...

  4. mac安装软件运行提示「xxx.app已损坏,打不开.你应该将它移到废纸篓」的解决办法

    「xxx.app已损坏,打不开.你应该将它移到废纸篓」,其实并非你安装的软件已损坏,而是Mac系统的安全设置问题,往往这些软件可能是经过了汉化或者破解,所以被Mac认为「已损坏」,那么解决方法就是临时 ...

  5. 谱曲软件-MuseScore

    谱曲软件-MuseScore 参考: 1.MuseScore官网 2.免费乐谱制作软体MuseScore

  6. LNK1123: 转换到 COFF 期间失败: 文件无效或损坏[汇总]

    目前有两种方式可用于解决: 1. 微软官方的一个解决方案: http://support.microsoft.com/kb/320216/zh-cn 发现是嵌入清单的问题,于是对该工程以及所有依赖工程 ...

  7. Nginx+keepalived实现负载均衡

    Nginx的优点是: 1.工作在网络的7层之上,可以针对http应用做一些分流的策略,比如针对域名.目录结构,它的正则规则比HAProxy更为强大和灵活,这也是它目前广泛流行的主要原因之一,Nginx ...

  8. HDOJ(1005) Number Sequence

    这道题,咋一看很像Fibonacci数列,使用递归或者改进的动态规划来解决.但是仔细一看,(1 <= n <= 100,000,000),使用这些方法,要么超时,要么肯定内存不够用,因此必 ...

  9. WebBench简介

    /** @brief     Web Bench Description* @author  Tang Huaming* @qq        1426213638* @E-mail   xiaoma ...

  10. PHP递归

    <?php /** * Mr.xml * 处理无限级分类 */ class Category{ /** * [递归一维数组] * @param [type] $cate [传递一个数组$cate ...