Spring-03(代理模式与AOP)

一.代理模式

代理模式就是SpringAOP的底层,它分为静态代理和动态代理

1.形象理解

用租房的例子理解代理模式
Spring-03(代理模式与AOP)_第1张图片

2.静态代理

对上图的解释:

  • 租房:这个事件是抽象的,可以用java中的接口代替
  • 房东:这是一个真实的人,可以用一个类来代替,他有租房的意向,因此需要实现一个租房的接口。
  • 中介:这是一个真实的人,用一个类表示,他帮房东租房,也需要实现租房接口,然后去做本来应该房东做的所有租房的事。
  • 房客:这是一个真实的人,是一个类,我想租房子,首先要有房东,其次要有中介,然后我只需要面对中介就可以租到房子。

代码实现:

(1)编写接口(Rent)

   //租房
   public interface Rent {   
       public void rent();
   }

(2)编写房东这个类(Host)

   //房东
   public class Host implements Rent {  
       public void rent() {
           System.out.println("房东要出租房子!");
       }
   }

(3)编写中介这个类(Proxy)

   public class Proxy implements Rent {  
       private Host host;
   
       public Proxy() {
       }
       public Proxy(Host host) {
           this.host = host;
       }
       public void rent() {
           seeHouse();//看房
           host.rent();//租房
           hetong();//签合同
       }
   
       //看房
       public void seeHouse(){
           System.out.println("中介带你看房");
       }
   
       //签合同
       public void hetong(){
           System.out.println("签租赁合同");
       }
   }

(4)编写房客这个类(Client)

   public class Client {
       public static void main(String[] args) {
           //房东要租房子
           Host host = new Host();
           //中介帮房东租房子和干所有和租房有关的事
           Proxy proxy = new Proxy(host);
   
           //你不用面对房东,直接找中介租房即可!
           proxy.rent();
       }
   }

代理模式的好处:

  • (1)可以使真实角色(ps:房客)的操作更加纯粹!不用去关注一些公共的业务
  • (2)公共业务就交给代理角色!实现了业务的分工!
  • (3)公共业务发生扩展的时候,方便集中管理!

代理模式的缺点:

一个真实角色就会产生一个代理角色;代码量会翻倍开发效率会变低

3.动态代理

动态代理和静态代理角色一样,只不过它是动态生成的

动态代理分为三大类

  • 基于接口的动态代理— JDK 动态代理
  • 基于类的动态代理— cglib
  • java字节码实现— javasist

需要了解两个类 :Proxy:代理 ,InvocationHandler:调用处理程序

2.代码演示

(1)编写接口和需要代理的类

public interface Rent {
    public void rent();
}
public class Host implements Rent {
    public void rent() {
        System.out.println("租房");
    }
}

(2)编写动态代理类(ProxyInvocationHandler.class)

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyInvocationHandler implements InvocationHandler {
    //被代理的接口
    private Rent rent;

    public void setRent(Rent rent) {
        this.rent = rent;
    }
    //生成得到代理类
    public Object getProxy(){
        return Proxy.newProxyInstance(this.getClass().getClassLoader(),rent.getClass().getInterfaces(),this);
    }
    //处理代理实例,并返回结果
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //动态代理的本质就是使用反射机制实现
        Object invoke = method.invoke(rent, args);
        return invoke;
    }
}

(3)编写用户类

public class Client {
    public static void main(String[] args) {
        //真实角色
        Host host = new Host();
        ProxyInvocationHandler handler = new ProxyInvocationHandler();
        //通过调用程序处理角色来处理我们要调用的接口对象
        handler.setRent(host);
        //生成代理对象
        Rent proxy = (Rent) handler.getProxy();
        proxy.rent();
    }
}

3.动态代理的好处:

  • 可以使真实角色的操作更加纯粹!不用去关注一些公共的业务
  • 公共也就就交给代理角色!实现了业务的分工
  • 公共业务发生扩展的时候,方便集中管理
  • 一个动态代理类代理的是一个接口,一般就是对应的一类业务
  • 一个动态代理类可以代理多个类,只要是实现了同一个接口即可

二.AOP

1.概述

面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。
AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。
利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

2.Aop在Spring中的作用

提供声明式事务;允许用户自定义切面
Aop可以在不改变原有代码的情况下 , 去增加新的功能

  • 横切关注点:跨越应用程序多个模块的方法或功能。即与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点。如日志 , 安全 , 缓存 , 事务等等 …
  • 切面(ASPECT):横切关注点被模块化的特殊对象。即它是一个类。
  • 通知(Advice):切面必须要完成的工作。即它是类中的一个方法。
  • 目标(Target):被通知对象。
  • 代理(Proxy):向目标对象应用通知之后创建的对象。
  • 切入点(PointCut):切面通知 执行的 “地点”的定义。
  • 连接点(JointPoint):与切入点匹配的执行点。

SpringAOP中,通过Advice定义横切逻辑,Spring中支持5种类型的Advice:
Spring-03(代理模式与AOP)_第2张图片

3.使用Spring实现Aop

(1)方式一:使用Spring的API 接口【主要SpringAPI接口实现】

第一步:导包

使用AOP织入,需要导入的依赖


<dependency>
    <groupId>org.aspectjgroupId>
    <artifactId>aspectjweaverartifactId>
    <version>1.9.4version>
dependency>

第二步:编写真实业务类

建立service包并在包下建立Userservice接口和它的实现类UserserviceImpl
接口Userservice

public interface Userservice {
    public void add();
    public void delete();
    public void update();
    public void select();
}

实现类UserserviceImpl

public class UserserviceImpl implements Userservice {
    public void add() {
        System.out.println("增加用户");
    }

    public void delete() {
        System.out.println("删除用户");
    }

    public void update() {
        System.out.println("更改用户");
    }

    public void select() {
        System.out.println("查询用户");
    }
}

第三步:编写日志类

建立log包并在包下建立Log类,前置日志

public class Log implements MethodBeforeAdvice {
    //method:要执行的目标对象的方法
    //args:参数
    //target:目标对象
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
    }
}

在log包下建立AfterLog 类,后置日志

public class AfterLog implements AfterReturningAdvice {
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("执行了"+method.getName()+"方法,返回结果为"+returnValue);
    }
}

第四步:在配置文件中注册

在resources包下建立配置文件applicationContext.xml


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">
    <bean id="userService" class="com.yl.service.UserserviceImpl" />
    <bean id="log" class="com.yl.log.Log" />
    <bean id="afterLog" class="com.yl.log.AfterLog" />
    <aop:config>
        <aop:pointcut id="pointcut" expression="execution(* com.yl.service.UserserviceImpl.*(..))" />
        <aop:advisor advice-ref="log" pointcut-ref="pointcut" />
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut" />
    aop:config>
beans>

第五步:测试

public class Ceshi {
    @Test
    public void test1(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Userservice userService = (Userservice) context.getBean("userService");
        userService.delete();
    }
}

(2)方式二 : 自定义来实现AOP 【主要是切面定义】

前两步相同

第三步:自定义切入点类

在diy包下建立DiyPointCut类

public class DiyPointCut {
    public void before(){
        System.out.println("---------执行前---------");
    }
    public void after(){
        System.out.println("---------执行后---------");
    }
}
第四步:注册bean

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">
    <bean id="userService" class="com.yl.service.UserserviceImpl" />
    <bean id="diy" class="com.yl.diy.DiyPointCut" />
    <aop:config>
        <aop:aspect ref="diy">
            <aop:pointcut id="pointcut" expression="execution(* com.yl.service.UserserviceImpl.*(..))"/>
            <aop:before method="before" pointcut-ref="pointcut" />
            <aop:after method="after" pointcut-ref="pointcut" />
        aop:aspect>
    aop:config>
beans>

第五步:测试同上

(2)方式三 : 使用注解实现

前两步相同

第三步:编写注解方式的类

建立AnnotationPointCut类

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
public class AnnotationPointCut {
    @After("execution(* com.yl.service.UserserviceImpl.*(..))")
    public void after(){
        System.out.println("=====执行后=====");
    }
    @Before("execution(* com.yl.service.UserserviceImpl.*(..))")
    public  void before(){
        System.out.println("=====执行前=====");
    }
    @Around("execution(* com.yl.service.UserserviceImpl.*(..))")
    public void around(ProceedingJoinPoint jp) throws Throwable {
        System.out.println("=====环绕前=====");
        Object proceed = jp.proceed();
        Signature signature = jp.getSignature();

        System.out.println(signature);
        System.out.println("=====环绕后=====");
        System.out.println(proceed);
    }
}

第四步:注册bean


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">
    <bean id="userService" class="com.yl.service.UserserviceImpl" />
<bean id="annotationPointCut" class="com.yl.diy.AnnotationPointCut" />
    <aop:aspectj-autoproxy />
beans>

第五步:测试同上

你可能感兴趣的:(java)