九点钟☆方向

记录成长点滴

欢迎来到我的个人博客~


Spring笔记(七) Spring AOP

目录

代理模式

通过代理类为原始类增加额外功能,不修改源码的基础上对方法进行增强

代理类的本质=原始类+额外功能+实现原始类相同接口

静态代理

字节码一上来就创建好,并完成加载。装饰者模式就是静态代理的一种体现。

以租房为例:在原有房东类的基础上,增加一个中介类添加额外功能,并实现房东类的租房方法

4

静态代理的缺点:

  1. 代理类的数量过多 不利于项目管理
  2. 额外功能代码冗余
  3. 替换代理的额外功能 麻烦

动态代理

字节码随用随创建,随用随加载

动态代理常用的两种方式

基于接口的动态代理

提供者: JDK 官方的 Proxy 类。 要求:被代理类最少实现一个接口。

如何创建:使用Proxy类的newProxyInstance()方法

//以销售电脑为例

//生产者接口
public interface IProducter {
    public void saleProduct(Float money);//销售方法
    public void afterProduct(Float money);//售后方法
}

//生产者实现类
public class ProducterImpl implements IProducter {
    public void saleProduct(Float money) {
        System.out.println("生产者的销售方法"+money);
    }

    public void afterProduct(Float money) {
        System.out.println("生产者的售后方法"+money);
    }
}

//消费者(使用动态代理,相当于不找生产者买电脑,而找代理商)
public class Client {
    public static void main(String[] args) {
        //匿名内部类访问外部类成员时,要求外部类成员为final
        final IProducter producter = new ProducterImpl();

        IProducter producterProxy = (IProducter)Proxy.newProxyInstance(
            producter.getClass().getClassLoader(),//被代理对象的类加载器
            producter.getClass().getInterfaces(),//被代理对象的接口,为保证二者具有相同的方法
            new InvocationHandler() {//增强的方法,匿名内部类
              public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        Object returnVal = null;
                        Float money = (Float) args[0];
                  //如果是销售方法,代理商要收20%,支付1万厂家只能收到8000
                        if ("saleProduct".equals(method.getName())) {
                            //代表方法执行 
                            returnVal = method.invoke(producter,money * 0.8f);
                        }
                        return returnVal;
                    }
                });

        producterProxy.saleProduct(1000f);
    }
}

细节:
1.
Proxy.newProxyInstance(ClassLoader loader,Class<?>[] interfaces,InvocationHandler h)
参数
	loader和被代理对象使用相同的类加载器
	interfaces和被代理对象具有相同的行为实现相同的接口
	h如何代理也就是增强的方法
	
2.	
public Object invoke(Object proxy, Method method, Object[] args) 
作用执行被代理对象的任何接口方法都会经过该方法此方法有拦截的作用
参数
	proxy代理对象的引用
	method当前执行的方法
	args:当前执行方法所需要的参数
返回值和被代理对象方法有相同的返回值

3.
method.invoke(Object obj, Object... args)
作用代表方法执行
参数
	obj被代理对象
	args方法参数
基于子类的动态代理

提供者:第三方的CGlib,如果报asmXXX异常,需要导入asm.jar

要求:被代理对象不能是最终类 (用final修饰的类)

用到的类:Enhancer

如何创建:使用Enhancer 类的create方法

  1. 导入cglib依赖

    <dependency>
        <groupId>cglib</groupId>
        <artifactId>cglib</artifactId>
        <version>3.2.9</version>
    </dependency>
    
  2. java代码

    public class Client1 {
        public static void main(String[] args) {
            final ProducterServiceImpl producter = new ProducterServiceImpl();
            Enhancer enhancer = new Enhancer();
       
            ProducterServiceImpl cglibProducter = (ProducterServiceImpl) enhancer.create(
                producter.getClass(), 
                new MethodInterceptor() {
                public Object intercept(Object o, Method method, Object[] objects, 
                                        MethodProxy methodProxy) throws Throwable {
                    Object returnVal = null;
                    Float money = (Float) objects[0];
                    if("saleProduct".equals(method.getName())) {
                        returnVal = method.invoke(producter,money*0.8f);
                    }
                    return returnVal;
                }
            });
       
            cglibProducter.saleProduct(1000f);
        }
    }
       
    细节
    1.
    public static Object create(Class type, Callback callback)
    参数
    	type被代理对象的字节码
    	callback如何代理用于提供增强的代码通常也是匿名内部类一般都是写callback接口的子接口实现类MethodInterceptor
       	
    2.
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy)
    作用执行被代理对象的任何方法都会经过该方法在此方法内部就可以对被代理对象的任何方法进行增强
    参数
    	o:代理对象的引用和基于接口的动态代理是一样的
    	method当前执行的方法和基于接口的动态代理是一样的
    	objects当前执行方法所需的参数和基于接口的动态代理是一样的
    	methodProxy当前执行方法的代理对象
    返回值和被代理对象方法有相同的返回值
    

AOP

全称是 Aspect Oriented Programming 即: 面向切面编程。通过预编译的方式和运行期动态代理实现程序功能的统一维护的一种技术。利用AOP可以对业务逻辑的各个部门进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高开发效率。

简单的说它就是把我们程序重复的代码抽取出来,在需要执行的时候,使用动态代理的技术,在不修改源码的 基础上,对我们的已有方法进行增强

AOP 的作用及优势

作用:在程序运行期间,不修改源码对已有方法进行增强。 优势:

  1. 减少重复代码
  2. 提高开发效率
  3. 维护方便

AOP 的实现方式

使用动态代理技术

Spring中的AOP

关于代理的选择

Spring框架会根据目标类是否实现了接口来决定采用那种动态代理方式

AOP的想关术语

  1. Joinpoint(连接点):指那些被拦截到的点。在spring中,这些点指的是方法,因为spring只支持方法类型的连接点
  2. Pointcut(切入点):指我们要对哪些 Joinpoint 进行拦截,即要增强的方法
  3. Advice(通知/增强): 拦截到 Joinpoint 之后所要做的事情就是通知。通知氛围前置通知,后置通知,异常通知,最终通知,环绕通知。
  4. Introduction(引介): 引介是一种特殊的通知在不修改类代码的前提下, Introduction 可以在运行期为类动态地添加一些方法或 Field
  5. Target(目标对象): 代理的目标对象
  6. Weaving(织入):是指把增强应用到目标对象来创建新的代理对象的过程。 spring 采用动态代理织入,而 AspectJ 采用编译期织入和类装载期织入
  7. Proxy(代理): 一个类被 AOP 织入增强后,就产生一个结果代理类
  8. Aspect(切面): 是切入点和通知(引介)的结合。

AOP示例

模拟实现一个日志功能

导入依赖

<!--导入spring-context 和 aspectjweaver:用于解析切入点表达式的-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.2.8.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.2</version>
</dependency>

账户的业务层接口

public interface IAccountService {
    void saveAccount();//无返回值无参数
    void updateAccount(int i);//无返回值有参数
    int deleteAccount();//有返回值无参数
}

账户的业务层实现类

public class AccountServiceImpl implements IAccountService {
    public void saveAccount() {
        System.out.println("saveAccount");
    }

    public void updateAccount(int i) {
        System.out.println("updateAccount");
    }

    public int deleteAccount() {
        System.out.println("deleteAccount");
        return 0;
    }
}

日志类

public class Logger {
    public void printLog() {
        System.out.println("打印日志");
    }
}

创建Spring的配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!--beans里面需要导入AOP的约束-->
<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
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/aop
                           http://www.springframework.org/schema/aop/spring-aop.xsd">
    
    <bean id="accountService" class="com.mg.service.impl.AccountServiceImpl"></bean>
    <bean id="logger" class="com.mg.log.Logger"></bean>
    <aop:config>
        <aop:aspect id="logAdvice" ref="logger">
            <aop:before method="printLog" pointcut="execution(public void com.mg.service.impl.
                                                    AccountServiceImpl.saveAccount())">
            </aop:before>
        </aop:aspect>
    </aop:config>
</beans>

配置步骤:
1. 配置Service对象
2. 把通知类也交由Spring管理
3. 使用 aop:config 标签声明开始 aop 配置
4. 使用 aop:aspect 配置切面
	属性:
	id: 给切面提供一个唯一标识。
	ref: 引用配置好的通知类 bean 的 id。
5. 在aop:aspect内部使用 aop:xxx 配置对应的通知类型。aop:before表示前置通知
	属性:
	method:用于指定通知类中的哪个方法作为相应的通知
	ponitcut-ref:用于指定切入点的表达式的引用
	poinitcut:用于指定切入点表达式
6. 配置切入点表达式
	写法:execution(表达式)

打赏一个呗

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦