• 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();

  • 相关阅读:
    day6_redis模块和pipeline
    day6_hashlib模块
    18 MySQL数据导入导出方法与工具介绍之二
    【Vijos1264】神秘的咒语
    【Vijos1180】选课
    【vijos1234】口袋的天空
    【vijos1790】拓扑编号
    【WC2008】【BZOJ1271】秦腾与教学评估(二分,前缀和,奇偶性乱搞)
    【Baltic2003】【BZOJ1370】Gang团伙(并查集,拆点)
    【基础】二分算法学习笔记
  • 原文地址:https://www.cnblogs.com/zcjyzh/p/9367403.html
Copyright © 2020-2023  润新知