zoukankan      html  css  js  c++  java
  • 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();

  • 相关阅读:
    简单的分页存储过程,Json格式日期转换为一般日期
    事件的那些事
    关于1Byte 1K 1M 1G(换算)
    VS自带WCF测试客户端简单介绍
    “System.Transactions.Diagnostics.DiagnosticTrace”的类型初始值设定项引发异常[WCF]
    周末大放送网站图片上传,水印,预览,截图
    FIREDAC驱动ORACLE的配置
    匿名方法实现多线程同步到主线程执行
    DELPHI跨平台的临界替代者
    三层数据库设计注意事项
  • 原文地址:https://www.cnblogs.com/zcjyzh/p/9367403.html
Copyright © 2011-2022 走看看