在idea中利用Spring进行面向切面编程(AOP)的一个例子

来源:互联网 发布:sql添加默认值约束 编辑:程序博客网 时间:2024/04/29 21:02

(1)在idea中新建立一个maven项目aopAspectj,,编写POM文件,导入jar包:

<dependencies>    <!--aspectj依赖-->    <dependency>        <groupId>org.aspectj</groupId>        <artifactId>aspectjrt</artifactId>        <version>1.8.10</version>    </dependency>    <dependency>        <groupId>org.aspectj</groupId>        <artifactId>aspectjtools</artifactId>        <version>1.8.10</version>    </dependency>    <!--spring相关包-->    <dependency>        <groupId>org.springframework</groupId>        <artifactId>spring-web</artifactId>        <version>4.3.1.RELEASE</version>    </dependency>    <dependency>        <groupId>org.springframework</groupId>        <artifactId>spring-webmvc</artifactId>        <version>4.3.1.RELEASE</version>    </dependency></dependencies>
(2)编写一个接口:Performance(可以代表任何类型的现场表演)
public interface Performance {    public void perform();}

(3)实现接口Performance方法。创建了一个歌舞剧表演

public class Theatre implements Performance{    public void perform(){        System.out.println("50个人正在表演舞台剧");    }}


(4)使用注解@Aspect来定义切面。在表演之前的动作有silenceCellPhonestakeSeats。表演成功后的动作:applause。表演异常的动作有demandRefund

@Aspect //表明该类别是一个切面public class Audience {    @Pointcut("execution(** Performance.perform(..))")  //定义命令的切点    public void performance(){}    @Before("performance()")    //在表演之前    public void silenceCellPhones(){        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");    }}


其中@Pointcut是用来定义performance(),使它可以代表含义"execution(** Performance.perform(..))"



(5)然后创建配置类ConcertConfig,用来把Aspectj自启动代理。其中@EnableAspectJAutoProxy来启动Aspectj代理。

@Configuration@EnableAspectJAutoProxy //启用Aspectj自动代理public class ConcertConfig {    @Bean   //声明了一个切面bean    public Audience audience(){        return new Audience();    }    @Bean    public Performance theatre(){        return new Theatre();    }}


(6)测试主类PerformanceTest

ublic class PerformanceTest {    public static void main(String[] args){        //加载java配置类获取Spring应用上下文        ApplicationContext ac=new AnnotationConfigApplicationContext(ConcertConfig.class);        //获取播放器        Performance pf=ac.getBean(Performance.class);        //播放        pf.perform();    }}


(7)结果显示:







1 0
原创粉丝点击