第一个AOP程序开发实例

spring用过,但是没有系统的学习过,最近工作不是很忙,所以找了本书(SPRING实战)学习下,然后在这里也算做个笔记吧。
一直都知道spring有两大宝:IOC和AOP。AOP在曾经做的项目中没有用到,所以一直不甚明白。这次机会让我可以一点点打开其神秘面纱
下面开始介绍我的小程序了:
定义Performer接口:

package com.study.spring.aop;

public interface Performer {
public void perform();
}


定义一个Performer的实现类Juggler:

package com.study.spring.aop;

public class Juggler implements Performer {
private int bagBeans = 3;
public Juggler() {}
public Juggler(int bagBeans) {
this.bagBeans = bagBeans;
}
public void perform() {
System.out.println("perform" + bagBeans);
}
}



定义切面类

package com.study.spring.aop;

public class Audience {
public void takeSeats() {
System.out.println("The audience is taking their seats");
}
public void turnOffCellphones() {
System.out.println("The audience is turning off their cellphones");
}
public void applaud() {
System.out.println("CLAP CLAP CLAP CLAP CLAP CLAP ");
}
public void demandRefund() {
System.out.println("Boo! We want our money back");
}
}

spring配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.1.xsd"
xmlns:aop="http://www.springframework.org/schema/aop">

<bean id="juggler" class="com.study.spring.aop.Juggler">
<constructor-arg value="15" />
</bean>

<bean id="audience" class="com.study.spring.aop.Audience" />

<aop:config>
<aop:aspect ref="audience">
<aop:pointcut id="performance"
expression="execution(* com.study.spring.aop.Performer.perform(..))" />

<aop:before pointcut-ref="performance" method="takeSeats" />
<aop:before pointcut-ref="performance" method="turnOffCellphones" />
<aop:after-returning pointcut-ref="performance"
method="applaud" />
<aop:after-throwing pointcut-ref="performance"
method="demandRefund" />

</aop:aspect>
</aop:config>
</beans>


定义测试类:

package com.study.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.study.spring.aop.Performer;

public class Test {

public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ctx = null;
ctx = new ClassPathXmlApplicationContext("com/study/spring/spring.xml");
Performer performer = (Performer) ctx.getBean("juggler");
performer.perform();
}

}


执行结果:

The audience is taking their seats
The audience is turning off their cellphones
perform15
CLAP CLAP CLAP CLAP CLAP CLAP
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值