一、

假设有情形如: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. sql查询某段时间内的数据

    查询半小时内数据的方法 1.select * from 表名 where datediff(minute,createtime,getdate())<30 2.select * from 表名 ...

  2. Android logcat使用

    Android logcat使用 1. Android日志说明 当Android系统运行的时候,会搜集所有的系统信息. logcat是Android系统的一个命令行工具,主要用来查看和过滤日志信息. ...

  3. selenium简单代码入门

    #!/usr/bin/env python #-*- coding:utf-8 -*- import os,sys,string import time import unittest from se ...

  4. ###STL学习--迭代器

    点击查看Evernote原文. #@author: gr #@date: 2014-08-23 #@email: forgerui@gmail.com STL中的迭代器. ###stl学习 |--迭代 ...

  5. 利用Ajax改变发送请求方式

    由于测试的时候需要模拟Head请求,解决办法:先访问要请求的站点,然后在浏览器的控制台下执行如下代码,请求方式就为参数给的值: var xmlHttp; if (window.ActiveXObjec ...

  6. 第一篇、Swift_Textkit的基本使用

    简介: iOS7 的发布给开发者的案头带来了很多新工具.其中一个就是 TextKit(文本工具箱).TextKit 由许多新的 UIKit 类组成,顾名思义,这些类就是用来处理文本的. 1.NSTex ...

  7. 判断对象是不是Vector

    判断对象是不是数组可以用 var arr:Array = []; trace(arr is Array);//true var vec:Vector.<String> = new Vect ...

  8. SQL Constraint/Index

    1.SQL Constraint Integrity Constraints are used to apply business rules for the database tables. The ...

  9. 九度OJ 1104 整除问题

    题目地址:http://ac.jobdu.com/problem.php?pid=1104 题目描述: 给定n,a求最大的k,使n!可以被a^k整除但不能被a^(k+1)整除. 输入: 两个整数n(2 ...

  10. Poj 1054 The Troublesome Frog / OpenJudge 2812 恼人的青蛙

    1.链接地址: http://poj.org/problem?id=1054 http://bailian.openjudge.cn/practice/2812 2.题目: 总时间限制: 10000m ...