Loading

第十五章 Spring动态代理开发

1.Spring动态代理的概念

概念: 通过代理类为原始类(目标类)增加额外功能
好处: 利于原始类的维护

2.搭建开发环境

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    <version>5.3.20</version>
</dependency>
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjrt</artifactId>
    <version>1.9.9.1</version>
</dependency>
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.9.1</version>
</dependency>

3.Spring动态代理的开发步骤

  1. 创建原始对象

    public class UserServiceImpl implements UserService{
        @Override
        public void register(User user) {
            System.out.println("UserServiceImpl.register");
        }
        @Override
        public boolean login(String username, String password) {
            System.out.println("UserServiceImpl.login");
            return true;
        }
    }
    
    <bean id="userService" class="com.dong.proxy.UserServiceImpl"/>
    
  2. 额外功能

    实现MethodBeforeAdvice接口

    额外功能书写在接口的实现中,在原始方法执行之前运行额外功能
    
    public class Before implements MethodBeforeAdvice {
        @Override
        public void before(Method method, Object[] args, Object target) throws Throwable {
            System.out.println("-----log:MethodBeforeAdvice-------");
        }
    }
    
    <bean id="before" class="com.dong.dynamic.Before"/>
    
  3. 定义切入点

    切入点: 额外功能加入的位置(哪个方法)
    目的: 由程序员根据自己需要,决定额外功能加入那个原始方法
    
    <aop:config>
        <!--为所有的方法加上额外功能,切入点为所有方法-->
        <aop:pointcut id="before" expression="execution(* *(..))"/>
    </aop:config>
    
  4. 组装

    整合二三步
    
    <aop:config>
        <!--为所有的方法加上额外功能,切入点为所有方法-->
        <aop:pointcut id="bef" expression="execution(* *(..))"/>
        <!--额外功能定义在Before类,切入点是UserService中的所有方法-->
        <aop:advisor advice-ref="before" pointcut-ref="bef"/>
    </aop:config>
    
  5. 调用

    目的: 获得Spring工厂创建的动态代理对象,并进行调用
    注意: 
    	1. Spring工厂通过原始对象的id值获得的是代理对象
    	   context.getBean("userService")
    	2. 获得代理对象后,可以通过声明接口类型,进行存储(代理对象和原始对象实现相同接口)
    	   UserService userService = context.getBean("userService")
    

4.动态代理的细节分析

  1. Spring创建的动态代理类在哪里?

    Spring框架在运行时,通过动态字节码技术,在JVM中创建,运行在JVM内部.等程序结束后,会和JVM一起消失
    所以不会和静态代理一样,类文件过多,影响项目管理
    
  2. 什么是动态字节码技术?

    通过第三方字节码框架,在JVM中创建对应类的字节码,进而创建对象,当虚拟机结束,动态字节码跟着消失
    

image

  1. 动态代理编程简化代理的开发

    在额外功能不改变的前提下,创建其他原始类的代理对象时,只要在aop:advisor标签中指定原始对象即可
    
  2. 动态代理额外功能维护性增强

    在程序开发中遵循一个原则: 打开拓展,关闭修改
    当我们对额外功能不满意时,我们不必去修改额外功能代码,只需新建一个额外功能,然后在配置文件中,修改标签即可
    
posted @ 2022-07-22 13:02  苏无及  阅读(61)  评论(0编辑  收藏  举报