欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

详解Spring 基于 Aspect 注解的增强实现

程序员文章站 2024-02-28 11:18:58
整理文档,搜刮出一个spring 基于 aspect 注解的增强实现的代码,稍微整理精简一下做下分享 定义基本实体类 package com.advice;...

整理文档,搜刮出一个spring 基于 aspect 注解的增强实现的代码,稍微整理精简一下做下分享

定义基本实体类

package com.advice;

/**
 * @author duoduo
 * @version 1.0
 * @date 2017/4/25 23:41
 */
public class performer {

  public void doperform() {
    system.out.println("performer do perform ....................... ");
  }
}

定义基于注解的增强类

package com.advice;

import org.aspectj.lang.proceedingjoinpoint;
import org.aspectj.lang.annotation.*;

/**
 * @author duoduo
 * @version 1.0
 * @date 2017/4/25 23:42
 */

@aspect//定义切面
public class audience {

  //定义切点
  @pointcut("execution(* com.advice.performer.doperform(..))")
  public void doperform(){}

  @before("doperform()")
  public void takeseas() {
    system.out.println("the audience is taking their seats.");
  }

  @before("doperform()")
  public void turnoffphone() {
    system.out.println("the audience is turn off their cellphone.");
  }

  @afterreturning("doperform()")
  public void applaund() {
    system.out.println("clap clap clap clap ...");
  }

  @afterthrowing("doperform()")
  public void demandrefund() {
    system.out.println("boo! we want our money back!");
  }

  @around("doperform()")
  public void watchperfomance(proceedingjoinpoint joinpoint) {

    try {
      long start = system.currenttimemillis();

      joinpoint.proceed();

      long end = system.currenttimemillis();

      system.out.println("the performance took "+(end-start)+" milliseconds");

    } catch (throwable throwable) {
      throwable.printstacktrace();
    }


  }
}

spring 自动代理配置

<!-- aop 增强自动代理 -->
<aop:aspectj-autoproxy/>
<bean id="audience" class="com.advice.audience"/>
<bean id="performer" class="com.advice.performer"/>

junit测试

@test
  public void testdoperform() throws exception {
    applicationcontext context = new classpathxmlapplicationcontext("classpath:smart-context.xml");
    //代理为指向interface的代理
    performer performer = (performer) context.getbean("performer");

    system.out.println("+++++++++++++++++++++++++++++++++");
    performer.doperform();
  }

测试结果

+++++++++++++++++++++++++++++++++
2017-04-26 20:51:16,980 debug [main] (abstractbeanfactory.java:251) - returning cached instance of singleton bean 'audience'
the audience is taking their seats.
the audience is turn off their cellphone.
performer do perform ....................... 
the performance took 91 milliseconds
clap clap clap clap ...

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。