Spring-AOP为类增加新的功能

适配器的简单应用实现:

  比如:有一个类Car,在类中有两个属性一个为汽车名name,另一个为速度speed。其行为为run()。

     现在有一辆车BMWCar 增加了GPS功能。如下实现:

      基本类:

      public class Car{

        private String name;

        private double speed;

        public void run()

      }

      新增功能:

      public interface GPS{}

      实现继承基本类,再实现新增接口:

      public class BMWCar extends Car implements GPS{}

利用Spring-AOP实现:

   package com.springaop.test; 

    public interface Car{

      public void run();

    }

    public class BMWCar implements Car{

      public void run(){}

    }

    //新增功能

    public interface GPS{

      public void gpsLocation();

    }

    public class GPSCar implements GPS{

      public void gpsLocation(){}

    }

通过配置AOP,实现两种功能的耦合:


<beans>
  <bean id="car" class="com.springaop.test.Car"/>
  <bean id="bmwcr" class="com.springaop.test.BMWCar"/>

  <aop:config proxy-target-class="true">
    <aop:aspect>
      <aop:declare-parents

        <!--- types-mathcing是之前原始的类 ->
        types-matching="com.springaop.test.Car"

        <!---implement-interface是想要添加的功能的接口 -->
        implement-interface="com.springaop.test.GPS"

        <!-- default-impl是新功能的默认的实现-->
        default-impl="com.springaop.test.GPSCar"/>
    </aop:aspect>
  </aop:config>
</beans>

测试:

  Car car = (Car)ctx.getBean("car");
  car.run();

  GPS gps = (GPS)ctx.getBean("car");

  gps.gpsLocation();

原文地址:https://www.cnblogs.com/zcjyzh/p/9367403.html