一、代理模式

代理模式的分类:

  • 静态代理
  • 动态代理

从租房子开始讲起:中介与房东有同一的目标在于租房

1.静态代理

静态代理角色分析:

  • 抽象角色:一般使用接口或者抽象类来实现(这里为租房接口)

    1. public interface Rent {
    2. void rent();
    3. }
  • 真实角色:被打理的角色(这里为房东)

    1. public class HouseMaster implements Rent{
    2. public void rent() {
    3. System.out.println("房东租房啦!");
    4. }
    5. public static void main(String[] args) {
    6. HouseMaster houseMaster = new HouseMaster();
    7. Proxy proxy = new Proxy(houseMaster);
    8. proxy.rent();
    9. }
    10. }
  • 代理角色:代理真实角色,代理真实角色后,一般会做一些附属操作

    1. public class Proxy {
    2. HouseMaster houseMaster;
    3. public Proxy() {
    4. }
    5. public Proxy(HouseMaster houseMaster) {
    6. this.houseMaster = houseMaster;
    7. }
    8. public void rent(){
    9. lookHouse();
    10. houseMaster.rent();
    11. sign();
    12. }
    13. public void lookHouse(){
    14. System.out.println("看房子");
    15. }
    16. public void sign(){
    17. System.out.println("签合同");
    18. }
    19. }
  • 客户:使用代理角色来进行一些操作

    1. public static void main(String[] args) {
    2. HouseMaster houseMaster = new HouseMaster();
    3. Proxy proxy = new Proxy(houseMaster);
    4. proxy.rent();
    5. }

    优点:

    (1).真实对象更加纯粹,不在关注一些琐碎的公共事务

    (2).公共业务由代理对象完成,有利于公共业务的扩展和管理

    缺点:多了代理对象也增加了代码量(所以后面出现了动态代理模式)

  1. 动态代理

    角色分析:与静态代理相同

    特点:动态代理的动态类是动态生成的,不是我们直接写好的

    分类:

    (1).基于接口的动态代理——JDK动态代理(重点理解)

    (2).基于类的动态代理——cglib

    (3).javasist

    核心api:

    (1).Proxy:

    Proxy提供了创建动态代理类和实例的静态方法,它也是由这些方法创建的所有动态代理类的超类。

    • newProxyInstance(ClassLoader loader, 类<?>[] interfaces, InvocationHandler h):返回指定接口的代理类的实例,该接口将方法调用分派给指定的调用处理程序。

      参数:

      (1).loader类加载器

      (2).代理对象的接口

      (3).InvocationHandler的实体,因为一般是调用类继承了InvocationHandler,所以许多时候就是this

    (2).InvocatioinHandler:

    InvocationHandler是由代理实例的调用处理程序实现的接口

    每个代理实例都有一个关联的调用处理程序(也就是一个代理类)。 当在代理实例上调用方法时,方法调用将被编码并分派到其调用处理程序的invoke方法。

    • invoke

      参数:

      (1).proxy:调用该方法的代理实例

      (2).method:所述方法对应于调用代理实例上的接口方法的实例

      (3).args:参数,如果没有则为null

    使用:

    1. 构建动态代理对象(这个代理对象可以用于同一个接口的多个实现类)

      1. public class ProxyInvocationHandler implements InvocationHandler {
      2. //代理对象
      3. Object target;
      4. //设定动态代理的对象
      5. public void setTarget(Object target){
      6. this.target = target;
      7. }
      8. public Object getProxy(){
      9. return Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
      10. }
      11. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
      12. Object res = method.invoke(target, args);
      13. return res;
      14. }
      15. }
    2. 测试

      1. public class service {
      2. public static void main(String[] args) throws Throwable {
      3. ProxyInvocationHandler handler = new ProxyInvocationHandler();
      4. handler.setTarget(new HostImpl());
      5. Host proxy = (Host) handler.getProxy();
      6. proxy.rent();
      7. }
      8. }
    3. 解释:从构建动态代理对象的过程查看

      (1).设定动态代理对象:setTarget()

      (2).获得动态代理getProxy()

      (3).使用动态代理,表面上看是调用了proxy.rent,本质上还是调用handler实现的invoke函数,注意该函数的第一个参数proxy用处不大

    优点:在静态代理的基础上,静态代理是代理的是一个类;而动态代理是代理一个接口(多个类)

二、AOP

AOP:面向切面编程,通过预编译方式和运行期动态代理实现 程序功能的统一维护的一种技术

导入织入包

两种方式:

  1. 使用api接口

    (1).MethodBeforeAdvice:方法的前置增强

    (2).AfterReturningAdvice:方法的后置增强

    环境搭建:

    1. //接口
    2. public interface service {
    3. void say();
    4. }
    5. //实例
    6. public class serviceImpl implements service {
    7. public void say() {
    8. System.out.println("say some thins");
    9. }
    10. }
    11. //前置增强
    12. public class beforeSay implements MethodBeforeAdvice {
    13. public void before(Method method, Object[] objects, Object o) throws Throwable {
    14. System.out.println("Good Morning!");
    15. }
    16. }
    17. //后置增强
    18. public class afterSay implements AfterReturningAdvice {
    19. public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
    20. System.out.println("后置增强");
    21. }
    22. }

    配置文件:

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <beans xmlns="http://www.springframework.org/schema/beans"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    4. xsi:schemaLocation="http://www.springframework.org/schema/beans
    5. https://www.springframework.org/schema/beans/spring-beans.xsd
    6. http://www.springframework.org/schema/aop
    7. https://www.springframework.org/schema/aop/spring-aop.xsd">
    8. <bean id="serviceImpl" class="com.guan.dao.serviceImpl"/>
    9. <bean id="beforeSay" class="com.guan.dao.beforeSay"/>
    10. <bean id="afterSay" class="com.guan.dao.afterSay"/>
    11. <aop:config>
    12. <!-- choose pointCut-->
    13. <!-- public method.(args)-->
    14. <aop:pointcut id="point" expression="execution(* com.guan.dao.service.*(..))"/>
    15. <aop:advisor advice-ref="beforeSay" pointcut-ref="point"/>
    16. <aop:advisor advice-ref="afterSay" pointcut-ref="point"/>
    17. </aop:config>
    18. </beans>

    注:

    (1).<aop:point>设定切入点

    (2).<aop:advisor>设定环绕对象(主要设定前置函数,后置函数及其目标的切入点)

    (3).execution(* com.guan.dao.service.*(..))execution(* com.guan.dao.*.*(..)):所有修饰符(public,private) com.guan.dao包下的所有类下的所有方法的所有参数

    测试:

    1. public static void main(String[] args) {
    2. ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    3. service bean = context.getBean("serviceImpl", service.class);
    4. bean.say();
    5. }

    注:这里返回的必须用接口类型(service),而不能用serviceImpl

  2. 使用切面

    环境搭建:

    1. package com.guan.dao;
    2. public class Advice {
    3. public void before(){
    4. System.out.println("before");
    5. }
    6. public void after(){
    7. System.out.println("after");
    8. }
    9. }

    配置文件:

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <beans xmlns="http://www.springframework.org/schema/beans"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    4. xsi:schemaLocation="http://www.springframework.org/schema/beans
    5. https://www.springframework.org/schema/beans/spring-beans.xsd
    6. http://www.springframework.org/schema/aop
    7. https://www.springframework.org/schema/aop/spring-aop.xsd">
    8. <bean id="advice" class="com.guan.dao.Advice"></bean>
    9. <bean id="serviceImpl" class="com.guan.dao.serviceImpl"></bean>
    10. <aop:config>
    11. <aop:aspect ref="advice">
    12. <aop:pointcut id="point" expression="execution(* com.guan.dao.serviceImpl.*(..))"/>
    13. <!-- 切面-->
    14. <aop:before method="before" pointcut-ref="point"></aop:before>
    15. <aop:after method="after" pointcut-ref="point"></aop:after>
    16. </aop:aspect>
    17. </aop:config>
    18. </beans>

    测试类:

    1. public static void main(String[] args) {
    2. ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    3. service bean = context.getBean("serviceImpl", service.class);
    4. bean.say();
    5. }
    6. //同上

    注:

    (1).注意<aop:aspect>的ref是相关的构成切面的类

    (2).在这个类的内部还是需要切入点的

  3. 使用api接口和使用切面比较

    (1).使用api接口需要记录相关的文档,但使用切面则可以在xml文件中直接配置

    (2).使用api接口需要多个类继承相关的接口,而使用切面只需要一个类承载相关的方法即可

    (3).使用api接口由于有对切入点的结果关联,所以和上下文的关联更密切;使用切面则切面的函数与切入点的上下文关系是割裂的

  4. 使用注解使用AOP

    相关注解:

    (1).@Aspect:标注这个类是一个切面

    (2).@Before("切入点")

    (3).@After("切入点后")

    (4).@Around:功能复杂,需要相关的方法使用ProceedingJoinPoint类型的参数,且这个参数可以直接调用方法

    (5).@EnableAspectJAutoProxy:用于注解开启注解(不用xml配置<aop:aspectj-autoproxy/>)

    注意:切入点都要用execution表达式

    环境搭建:

    1. @Aspect
    2. public class AnnotationCutPoint {
    3. @Before("execution(* com.guan.dao.*.*(..))")
    4. public void before(){
    5. System.out.println("before");
    6. }
    7. @After("execution(* com.guan.dao.*.*(..))")
    8. public void after(){
    9. System.out.println("after");
    10. }
    11. @Around("execution(* com.guan.dao.*.*(..))")
    12. public void around(ProceedingJoinPoint joinPoint) throws Throwable {
    13. System.out.println("around1");
    14. joinPoint.proceed();
    15. System.out.println("around2");
    16. }
    17. }

    注意:先要有切面@Aspect,才有切点

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <beans xmlns="http://www.springframework.org/schema/beans"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    4. xsi:schemaLocation="http://www.springframework.org/schema/beans
    5. https://www.springframework.org/schema/beans/spring-beans.xsd
    6. http://www.springframework.org/schema/aop
    7. https://www.springframework.org/schema/aop/spring-aop.xsd">
    8. <bean id="serviceImpl" class="com.guan.dao.serviceImpl"></bean>
    9. <bean id="annotation" class="com.guan.dao.AnnotationCutPoint"></bean>
    10. <aop:aspectj-autoproxy/>
    11. </beans>

    测试:

    1. public class serviceImpl implements service {
    2. public void say() {
    3. System.out.println("say some thins");
    4. }
    5. public static void main(String[] args) {
    6. ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    7. service bean = context.getBean("serviceImpl", service.class);
    8. bean.say();
    9. }
    10. }

    注:spring的AOP默认是通过jdk生成,但也可以进行修改

    1. <!-- jdk,默认-->
    2. <aop:aspectj-autoproxy proxy-target-class="false"/>
    3. <!-- cglib-->
    4. <aop:aspectj-autoproxy proxy-target-class="true"/>

spring——AOP(静态代理、动态代理、AOP)的更多相关文章

  1. 【spring基础】AOP概念与动态代理详解

    一.代理模式 代理模式的英文叫做Proxy或Surrogate,中文都可译为”代理“,所谓代理,就是一个人或者一个机构代表另一个人或者另一个机构采取行动.在一些情况下,一个客户不想或者不能够直接引用一 ...

  2. Spring AOP实现原理-动态代理

    目录 代理模式 静态代理 动态代理 代理模式 我们知道,Spring AOP的主要作用就是不通过修改源代码的方式.将非核心功能代码织入来实现对方法的增强.那么Spring AOP的底层如何实现对方法的 ...

  3. Spring Boot实践——Spring AOP实现之动态代理

    Spring AOP 介绍 AOP的介绍可以查看 Spring Boot实践——AOP实现 与AspectJ的静态代理不同,Spring AOP使用的动态代理,所谓的动态代理就是说AOP框架不会去修改 ...

  4. Spring AOP中的动态代理

    0  前言 1  动态代理 1.1 JDK动态代理 1.2 CGLIB动态代理 1.2.1 CGLIB的代理用法 1.2.2 CGLIB的过滤功能 2  Spring AOP中的动态代理机制 2.1  ...

  5. 转:Spring AOP中的动态代理

    原文链接:Spring AOP中的动态代理 0  前言 1  动态代理 1.1 JDK动态代理 1.2 CGLIB动态代理 1.2.1 CGLIB的代理用法 1.2.2 CGLIB的过滤功能 2  S ...

  6. spring---aop(4)---Spring AOP的CGLIB动态代理

    写在前面 前面介绍了Spring AOP的JDK动态代理的过程,这一篇文章就要介绍下Spring AOP的Cglib代理过程. CGLib全称为Code Generation Library,是一个强 ...

  7. 【Spring Framework】Spring入门教程(五)AOP思想和动态代理

    本文主要讲解内容如下: Spring的核心之一 - AOP思想 (1) 代理模式- 动态代理 ① JDK的动态代理 (Java官方) ② CGLIB 第三方代理 AOP概述 什么是AOP(面向切面编程 ...

  8. 转:AOP与JAVA动态代理

    原文链接:AOP与JAVA动态代理 1.AOP的各种实现 AOP就是面向切面编程,我们可以从以下几个层面来实现AOP 在编译期修改源代码 在运行期字节码加载前修改字节码 在运行期字节码加载后动态创建代 ...

  9. AOP与JAVA动态代理

    1.AOP的各种实现 AOP就是面向切面编程,我们可以从以下几个层面来实现AOP 在编译期修改源代码 在运行期字节码加载前修改字节码 在运行期字节码加载后动态创建代理类的字节码 2.AOP各种实现机制 ...

  10. 8、Spring教程之静态代理/动态代理

    为什么要学习代理模式,因为AOP的底层机制就是动态代理! 代理模式: 静态代理 动态代理 学习aop之前 , 我们要先了解一下代理模式! 静态代理 静态代理角色分析 抽象角色 : 一般使用接口或者抽象 ...

随机推荐

  1. 栈(stack)、递归(八皇后问题)、排序算法分类,时间和空间复杂度简介

    一.栈的介绍: 1)栈的英文为(stack)2)栈是一个先入后出(FILO-First In Last Out)的有序列表.3)栈(stack)是限制线性表中元素的插入和删除只能在线性表的同一端进行的 ...

  2. 虫师Selenium2+Python_3、Python基础

    P38--Python哲学 打开Python shell,输入import this,会看到下面的话: The Zen of Python, by Tim Peters   Beautiful is ...

  3. Oracle 获取表注释和列注释

    全部表 select table_name from user_tables; //当前用户拥有的表 select table_name from all_tables; //所有用户的表 selec ...

  4. Solution -「UR #2」「UOJ #32」跳蚤公路

    \(\mathcal{Description}\)   Link.   给定一个 \(n\) 个点 \(m\) 条边的带权有向图,每条边还有属性 \(s\in\{-1,0,1\}\).对于每个 \(u ...

  5. Node 模块规范鏖战:难以相容的 CJS 与 ESM

    自 13.2.0 版本开始,Node.js 在保留了 CommonJS(CJS)语法的前提下,新增了对 ES Modules(ESM)语法的支持. 天下苦 CJS 久已,Node 逐渐拥抱新标准的规划 ...

  6. 通过shell脚本批量操作mysql数据库

    创建建表语句 ============================================= 学生表:Student(Sno,Sname,Ssex,Sage,Sdept) ------(学 ...

  7. IDisposable?释放非托管资源接口

    原文:https://www.cnblogs.com/luminji/archive/2011/03/29/1997812.html IDisposable高级篇:https://docs.micro ...

  8. 【计算机基础】IL代码-CLR平台上的字节码【什么是字节码?它与虚拟机的关系?】

    字节码(英语:Bytecode)将虚拟机可以读懂的代码称之为字节码.将源码编译成虚拟机读的懂的代码,需要虚拟机转译后才能成为机器代码的中间代码 叫做字节码. 字节码主要为了实现特定软件运行和软件环境. ...

  9. 【windows 访问控制】十一、C# 实操 对象 System.Security.AccessControl 命名空间

    AccessControl 命名空间 结构图 解说: DirectorySecurity=目录ACLFileSecurity=文件ACLFileSystemAuditRule=目录和文件中SACL中的 ...

  10. .net mvc项目本地调试:浏览器一直转圈无法访问

    原因: 通过 bundles.Add 方式給多个 js文件添加 匿名,再通过  @Scripts.Render 引入的时候, js 里面使用了 const 来定义变量,就会导致访问pending,具体 ...