Spring 2.x 的新式Introduction Advice(引入通知) 配置

来源:互联网 发布:2016奥运会网络转播权 编辑:程序博客网 时间:2024/04/29 05:51
我看得是Spring in action,那里面的内容是Spring 1.1的,已经很过时的内容了, aop配置也是旧式的。在别人的提醒下,我开始看Spring 2.x的aop的新配置方法, 现在将这两天的研究结果写下来。

首先,新的有两种配置办法, 一是用注释配置, 二是用<aop>前缀的标签来配置, 这两种都是基于AspectJ的。以前的是Spring自己的AOP的API.


(一)写aspect

  1. public interface Shop {
  2.     public void service(Customer customer, String goods);
  3. }

  4. public class ShopImpl implements Shop {
  5.     public void service(Customer customer, String goods) {
  6.         customer.buy(good);
  7.         System.out.println("Shop: OK! " + goods + " for you");
  8.         customer.pay();
  9.     }
  10. }
还有就是例子所用到的Customer类
  1. public class Customer { 
  2.     public void buy(String goods) {
  3.         System.out.println("Customer: I want to buy " + goods);
  4.     }
  5.     
  6.     public void pay() {
  7.         System.out.println("Customer: This is the money");
  8.     }
  9. }
(二)增加引入通知

顾客走了,商店的人应该对顾客说拜拜,我们可以用AfterReturning来实现这个功能,但在这里,我决定尝试用Introduction Advice.

  1. public interface Bye {
  2.     public void sayBye();
  3. }
  4. public class ByeImpl implements Bye{
  5.     public void sayBye() {
  6.         System.out.println("Shop: Bye!");
  7.     }
  8. }
配置文件如下
  1. <bean id="shop" class="apple.spring.naop.ShopImpl" />
  2. <bean id="customer" class="apple.spring.naop.Customer" />
  3. <aop:aspectj-autoproxy />
  4.     <aop:config>
  5.         <aop:aspect ref="shop">
  6.             <aop:declare-parents 
  7.                 types-matching="apple.spring.naop.Shop+"
  8.                 implement-interface="apple.spring.naop.Bye"
  9.                 default-impl="apple.spring.naop.ByeImpl"/>
  10.         </aop:aspect>
  11.     </aop:config>
这里有一个关键,Shop要是一个接口,而不能是一个具体类


接下来是测试代码
  1. public static void main(String[] args) {
  2.         ApplicationContext ctx = new ClassPathXmlApplicationContext("aop.xml");
  3.         Shop shop = (Shop)ctx.getBean("shop");
  4.         Customer customer = (Customer)ctx.getBean("customer");
  5.         
  6.         shop.service(customer, "apple");
  7.         Bye bye = (Bye)shop;
  8.         bye.sayBye();
  9.     }
运行结果:

Customer: I want to buy apple
Shop: OK! apple for you
Customer: This is the money
Shop: Now shop is closed

注释的方式跟这个差不多
相信看官方文档应该可以看明白
原创粉丝点击