Spring AOP之使用注解创建切面

上节中我们已经定义了Performance接口,他是切面中的切点的一个目标对象。那么现在就让我们使用AspectJ注解来定义切面吧。

1.定义切面

下面我们就来定义一场舞台剧中观众的切面类Audience:

package com.spring.aop.service.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

/**
 * <dl>
 * <dd>Description:观看演出的切面</dd>
 * <dd>Company: 黑科技</dd>
 * <dd>@date:2016年9月3日 下午9:58:09</dd>
 * <dd>@author:Kong</dd>
 * </dl>
 */
@Aspect
public class Audience {

    
    /**
     * 目标方法执行之前调用
     */
    @Before("execution(** com.spring.aop.service.perform(..))")
    public void silenceCellPhone() {
        System.out.println("Silencing cell phones");
    }

    /**
     * 目标方法执行之前调用
     */
    @Before("execution(** com.spring.aop.service.perform(..))")
    public void takeSeats() {
        System.out.println("Taking seats");
    }

    /**
     * 目标方法执行完后调用
     */
    @AfterReturning("execution(** com.spring.aop.service.perform(..))")
    public void applause() {
        System.out.println("CLAP CLAP CLAP");
    }

    /**
     * 目标方法发生异常时调用
     */
    @AfterThrowing("execution(** com.spring.aop.service.perform(..))")
    public void demandRefund() {
        System.out.println("Demanding a refund");
    }

}

我们可以看到使用了几种注解,其实AspectJ提供了五中注解来定义通知:

注解 通知
@After 通知方法会在目标方法返回或抛出异常后调用
@AfterRetruening 通常方法会在目标方法返回后调用
@AfterThrowing 通知方法会在目标方法抛出异常后调用
@Around 通知方法将目标方法封装起来
@Before 通知方法会在目标方法执行之前执行

聪明的你可能已经看到,同样的切点我们写了四遍,这是不科学的,强大的Spring怎么会没有处理的方法呢。其实我们可以使用@Pointcut注解声明一个通用的切点,在后面可以随意使用:

package com.spring.aop.service.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

/**
 * <dl>
 * <dd>Description:观看演出的切面</dd>
 * <dd>Company: 黑科技</dd>
 * <dd>@date:2016年9月3日 下午9:58:09</dd>
 * <dd>@author:Kong</dd>
 * </dl>
 */
@Aspect
public class Audience {

    /**
     * 定义一个公共的切点
     */
    @Pointcut("execution(** com.spring.aop.service.Perfomance.perform(..))")
    public void performance() {
    }

    /**
     * 目标方法执行之前调用
     */
    @Before("performance()")
    public void silenceCellPhone() {
        System.out.println("Silencing cell phones");
    }

    /**
     * 目标方法执行之前调用
     */
    @Before("performance()")
    public void takeSeats() {
        System.out.println("Taking seats");
    }

    /**
     * 目标方法执行完后调用
     */
    @AfterReturning("performance()")
    public void applause() {
        System.out.println("CLAP CLAP CLAP");
    }

    /**
     * 目标方法发生异常时调用
     */
    @AfterThrowing("performance()")
    public void demandRefund() {
        System.out.println("Demanding a refund");
    }

}

这样定义一个切点后,后面我们的方法想使用这个切点直接调用切点所在的方法就行了。实际上切面也是一个Java类,我们可以将它装配到Spring中的bean中:

/**
 * 声明Audience bean
 * @return
 */
@Bean
public Audience audience(){
    return new Audience();
}

但是现在Spring还不会将Audience视为一个切面,即便使用了@AspectJ注解,但它并不会被视为一个切面们这些注解不会被解析,也不会创建将其转化为切面的代理。但我们可以使用JavaConfig,然后在JavaConfig类上使用注解@EnableAspectJAutoProxy注解启动自动代理功能:

package com.spring.aop.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

import com.spring.aop.service.aop.Audience;

/**
 * <dl>
 * <dd>Description:配置类</dd>
 * <dd>Company: 黑科技</dd>
 * <dd>@date:2016年9月3日 下午10:20:11</dd>
 * <dd>@author:Kong</dd>
 * </dl>
 */

@Configuration
//启动AspectJ自动代理
@EnableAspectJAutoProxy
@ComponentScan
public class ConcertConfig {
    
    /**
     * 声明Audience bean
     * @return
     */
    @Bean
    public Audience audience(){
        return new Audience();
    }

}

如果你想使用XML配置也是可以的,我们要使用Spring aop命名空间中的<aop:aspectj-autoproxy>元素:

<?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:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:cache="http://www.springframework.org/schema/cache"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/cache
        http://www.springframework.org/schema/cache/spring-cache.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd">
    

    <context:component-scan base-package="com.spring.aop" />\
    
    <!-- 启动AspectJ自动代理 -->
    <aop:aspectj-autoproxy/>
    
    <bean class="com.spring.aop.Audience" />
</beans>

其实不管使用JAvaConfig还是Xml,AspectJ都会为使用@ApsectJ注解的Bean创建一个代理,这个代理会环绕着所有该切面所匹配的bean。

2.创建环绕通知

环绕通知是这几种通知中相对复杂的一种,它可以在一个同时中同时编写前置和后置通知:

/**
 * 环绕通知
 * @param jp 通过它调用目标方法
 */
@Around("perforance()")
public void watchPerformance(ProceedingJoinPoint jp) {

    try {
        System.out.println("Silencing cell phones");
        System.out.println("Taking seats");
        jp.proceed();
        System.out.println("CLAP CLAP CLAP!!!");
    } catch (Throwable e) {
        System.out.println("Demanding a refund");
    }
}

3.处理通知中的参数

其实我们可以使用指示器args为切面中的方法传递参数,比如我们想统计唱片中每首歌曲的播放次数,这时我们想使用切面来完成这个工作,我们就需要向切面传递一个歌曲的编号,这时我们可以通过args向切面中的方法传递参数:

package com.spring.aop.service.aop;

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;

/**
 * <dl>
 * <dd>Description:统计每首歌曲播放次数的AOP</dd>
 * <dd>Company: 黑科技</dd>
 * <dd>@date:2016年9月4日 上午8:19:24</dd>
 * <dd>@author:Kong</dd>
 * </dl>
 */
@Aspect
public class TrackCounter {
        
    private Map<Integer,Integer> trackCounts = new HashMap<Integer,Integer>();
    
    @Pointcut("execution(* com.spring.aop.service.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;
        
    }
    
}

然后我们将这个切面配置到Spring中:

package com.spring.aop.config;

import java.util.List;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

import com.google.common.collect.Lists;
import com.spring.aop.service.CompactDisc;
import com.spring.aop.service.aop.TrackCounter;
import com.spring.aop.service.impl.BlankDisc;

/**
 * <dl>
 * <dd>Description:显示配置播放歌曲的bean和记录播放次数的AOP</dd>
 * <dd>Company: 黑科技</dd>
 * <dd>@date:2016年9月4日 上午8:52:05</dd>
 * <dd>@author:Kong</dd>
 * </dl>
 */
@Configuration
@EnableAspectJAutoProxy
public class TrackCounterConfig {
    
    @Bean
    public CompactDisc sgtPeppers(){
        BlankDisc cd = new BlankDisc();
        cd.setTitle("Sgt. Pepper's Lonely Hearts Club Band");
        cd.setArtist("The Beatles");
        
        List<String> tracks = Lists.newArrayList();
        tracks.add("Sgn. Pepper's Lonelu Hears Club Band");
        tracks.add("Wiith a Litter 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();
    }
}

为了证明他能够正常运行我们编写一个测试类进行测试:

package service;

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;

import com.spring.aop.config.TrackCounterConfig;
import com.spring.aop.service.CompactDisc;
import com.spring.aop.service.aop.TrackCounter;

/**
 * <dl>
 * <dd>Description: 测试统计歌曲播放的AOP</dd>
 * <dd>Company: 黑科技</dd>
 * <dd>@date:2016年9月4日 上午9:08:09</dd>
 * <dd>@author:Kong</dd>
 * </dl>
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TrackCounterConfig.class)
public class TrackCounterTest {

    @SuppressWarnings("deprecation")
    @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(4);
        cd.playTrack(2);
        cd.playTrack(4);
        cd.playTrack(2);
        
        assertEquals(1,counter.getPlayCount(1));
        assertEquals(3,counter.getPlayCount(2));
        assertEquals(1,counter.getPlayCount(3));
        assertEquals(2,counter.getPlayCount(4));
        assertEquals(0,counter.getPlayCount(5));
        assertEquals(0,counter.getPlayCount(0));
    }
}

运行后确定我们的代码是正确的!

4.通过注解引入新功能

像Java这种静态语言,一般一般类定义完成后,类中的方法属性就已经确定了,如果我们想要为这些类添加新方法、功能,就可以使用Spring Aop。现在我们想为所有的Performance实现引入下面的Encoreable接口:

package com.spring.aop.service;
/**
 * <dl>
 * <dd>Description:添加新功能</dd>
 * <dd>Company: 黑科技</dd>
 * <dd>@date:2016年9月4日 上午9:48:36</dd>
 * <dd>@author:Kong</dd>
 * </dl>
 */
public interface Encoreable {
    
    void performEncore();
}

要实现该功能我们要创建一个新的切面:

package com.spring.aop.service.aop;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.DeclareParents;

import com.spring.aop.service.Encoreable;
import com.spring.aop.service.impl.DefaultEncoreable;

/**
 * <dl>
 * <dd>Description:为目标bean添加新功能的AOP bean</dd>
 * <dd>Company: 黑科技</dd>
 * <dd>@date:201
 6年9月4日 上午9:45:34</dd>
 * <dd>@author:Kong</dd>
 * </dl>
 */
@Aspect
public class EncoreableIntroducer {
    
    @DeclareParents(value="com.spring.aop.service.Perforance+",defaultImpl=DefaultEncoreable.class)
    public static Encoreable encoreable;

}

我们可以看到在切面中它并没有使用前置、后置等通知的注解,而是使用了@DeclareParents注解,将Encoreable接口引入到Performance bean中。
@DeclareParents注解由三部分组成:

  • value属性指定了哪种类型的bean要引入该接口(加号表示是Performance的所有子类)。
  • defaultImpl属性指定了为引入功能提供实现类
  • @DeclareParents注解所标注的静态属性指明了要引入了接口,在这里,我们所引入的是Encoreable接口。

和其他切面一样,我们需要在Spring应用中将EncoreableIntroducer声明为一个bean:
<bean class="com.spring.aop.service.aop.EncoreableIntroducer" />
至此在Java类中配置切面的内容已经全部介绍完了,下节我们会介绍在XML中配置切面,一定很期待吧,那就赶紧来啊......

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,470评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,393评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,577评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,176评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,189评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,155评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,041评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,903评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,319评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,539评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,703评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,417评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,013评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,664评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,818评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,711评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,601评论 2 353

推荐阅读更多精彩内容

  • 本章内容: 面向切面编程的基本原理 通过POJO创建切面 使用@AspectJ注解 为AspectJ切面注入依赖 ...
    谢随安阅读 3,146评论 0 9
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,651评论 18 139
  • 当他不爱你的时候,你的爱便是他的负担。请不要去计算自己的付出,不要希望有什么回报。 爱着不爱自己的人...
    风雨一起走阅读 106评论 0 0
  • 今儿个见的客户很特别,她让我了解一个新定义,颠覆谁并不是让谁消失,是这个谁在别人的价值链中被边缘化了,如:有了微信...
    吕明超阅读 143评论 0 0
  • 这两天脾气爆了。昨天只看待产孕妇求剖腹产未果跳楼自杀的新闻,就有了想拿刀把那些逼得孕妇跳楼的家属给劈了。今天突然又...
    大漠铃儿响阅读 405评论 0 0