Spring框架AOP总结

**

喜欢有帮助记得点赞哦,加关注不迷路

**

一、AOP介绍

1.1、概述

        AOP的全称是Aspect Oriented Programming翻译过来就是面向切面编程,它的宗旨是在不修改源代码的前提下扩展功能,比如我们想要在代码原有的功能上去扩展功能在没有AOP的情况下就需要修改源代码,很不方便程序的扩展、维护,这将是一场灾难,有了AOP之后我们不用修改源代码就可以扩展功能,怎么理解切面呢?比如我们想要吃肉夹馍,在没有AOP的时候我们需要再做一个烙一个带肉的现成的肉夹馍,有了AOP之后呢,不需要重新烙一个馍,而是在馍的中间来一刀,这个就是切面,在中间加上肉就可以了。其实AOP是对OOP的补充,让我们开发程序变得更优雅

1.2、应用场景

        1、性能检测
        2、访问控制
        3、事务管理
        4、缓存
        5、日志模块等

1.3、AOP优点

        1、集中处理项目的业务问题抽取出来单独编写
        2、减少代码冗余
        3、提高程序的维护性和扩展性等

1.4、专业术语

        1、通知(Advice)
             就是扩展的功能,比如我们的程序中需要添加日志,事务等功能,我们当然需要将代码写好,封装到中,我们写好的这个方法就是通知,也可以称为增强,通知分为前置通知,后置通知,环绕通知,异常通知等,说明加在连接点的什么位置,什么时候调用。
        2、连接点(JoinPoint)
             可以增强的功能,比如添加、删除、修改、查询等方法。
        3、切入点(Pointcut)
             实际上增强的方法,就比如我们增强添加的功能,这个添加的方法就是切入点。
        4、切面(Aspect)
             我们之前的通知和连接点是相互独立没有联系的,切面就是将通知应用在连接点的过程,连接点就变成了真正被增强的方法,就变成了切入点。
        5、引入(introduction)
             允许我们向现有的类添加新方法属性。这不就是把切面(也就是新方法属性:通知定义的)用到目标类中吗
        6、目标(target)
             引入中所提到的目标类,也就是要被通知的对象,也就是真正的业务逻辑,他可以在毫不知情的情况下,被咱们织入切面。而自己专注于业务本身的逻辑。
        7、代理(proxy)
             怎么实现整套aop机制的,都是通过代理。
        8、织入(weaving)
             把切面应用到目标对象来创建新的代理对象的过程。有3种方式,spring采用的是运行时
这里重要的就是前四个

二、实现

2.1、实现方式

        在Spring中使用aspectj实现AOP操作,注意aspectj并不是Spring中的一部分,只是和Spring一起使用,Spring2.x之后支持对aspectj的支持。使用aspectj对AOP的操作实现有xml配置注解两种方式

2.2、pom依赖

        添加aop和aspectj依赖

<!--aop依赖-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    <version>${spring-version}</version>
</dependency>

<!-- aspectj支持 -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjrt</artifactId>
    <version>${aspectj-version}</version>
</dependency>
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>${aspectj-version}</version>
</dependency>

2.3、xml文件实现方式

2.3.1、业务类

package com.stt.service;

/**
 操作用户的Dao层
 */
public class UserService {

    //添加用户功能
    public void addUser(){
        System.out.println("添加用户");
    }
    //添加用户功能
    public void deleteUser(){
        System.out.println("删除用户");
    }
    //添加用户功能
    public void updateUser(){
        System.out.println("修改用户");
    }
    //添加用户功能
    public void queryUser(){
        System.out.println("查询用户");
    }
}

2.3.2、增强类

package com.stt.advice;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 用户的日志类,在对用户进行修改操作时添加上时间
 */
public class UserLog {

    /**
     * 前置通知:即在做增删改操作前调用该方法
     * 作用:生成时间
     */
    public void getTime(){
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = dateFormat.format(new Date());
        System.out.println("当前时间为"+time);
    }
    /**
     * 后置通知:即在做增删改操作后调用该方法
     * 作用:提示操作成功
     */
    public void success(){
        System.out.println("操作成功");
    }

}

2.3.3、applicationContext.xml

        本来对用户的操作只打印对应的信息,现在操作增删前会打印时间,操作会输出成功

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!--创建业务类对象-->
    <bean id="userService" class="com.stt.service.UserService"></bean>
    <!--创建增强类对象-->
    <bean id="userlog" class="com.stt.advice.UserLog"></bean>

    <!--配置aop-->
    <aop:config>
        <!--配置切入点,就是哪些方法要进行增强,这里需要写表达式
        execution(<访问修饰符>?<返回值类型><方法名>(<参数>)<异常>)
        1. execution (* com.stt.service.UserService.add*(..)) UserService类中以add开头的方法
        2. execution (* com.stt.service.UserService.*(..))UserService类中的所有方法
        3. execution (* *.*(..))所有方法
        4. execution (* save*(..))匹配所有save开头的方法
        ......
        多个表达式间使用 or 隔开
        -->
        <aop:pointcut id="pointcut1" expression="execution(* com.stt.service.UserService.addUser(..)) or
        execution(* com.stt.service.UserService.updateUser(..)) or
        execution(* com.stt.service.UserService.deleteUser(..))"></aop:pointcut>
        <!--配置切面
            将增强使用在切入点的过程
        -->
        <aop:aspect ref="userlog">
            <!--前置通知使用aop before标签
            method:填写增强类中的方法
            pointcut-ref:填写上班切入点的id
            -->
            <aop:before method="getTime" pointcut-ref="pointcut1"></aop:before>
            <!--后置通知使用after-->
            <aop:after method="success" pointcut-ref="pointcut1"></aop:after>
        </aop:aspect>
    </aop:config>


</beans>

2.3.4、测试

在这里插入图片描述
我们调用的是addUser方法但是该方法前后后有对应数据输出就是我们使用aop配置的,并没有修改UserService的源代码只是定义增强类和增强方法,使用xml配置文件将功能添加上去,极大提升我们的扩展性和维护性。

2.4、注解实现

2.4.1、业务类

package com.stt.service;

import org.springframework.stereotype.Service;

/**
 操作用户的Service层
 */
@Service("userService")
public class UserService {

    //添加用户功能
    public void addUser(){
        System.out.println("添加用户");
    }
    //添加用户功能
    public void deleteUser(){
        System.out.println("删除用户");
    }
    //添加用户功能
    public void updateUser(){
        System.out.println("修改用户");
    }
    //添加用户功能
    public void queryUser(){
        System.out.println("查询用户");
    }
}

2.4.2、增强类

package com.stt.advice;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 用户的日志类,在对用户进行修改操作时添加上时间
 * 添加@Aspect注解
 */
@Aspect
@Component("userLog")
public class UserLog {

    /**
     * 前置通知:即在做增删改操作前调用该方法
     * 作用:生成时间
     */
    @Before(value = "execution(* com.stt.service.UserService.addUser(..)) || " +
            " execution(* com.stt.service.UserService.updateUser(..)) || " +
            " execution(* com.stt.service.UserService.deleteUser(..))")
    public void getTime(){
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = dateFormat.format(new Date());
        System.out.println("当前时间为"+time);
    }
    /**
     * 后置通知:即在做增删改操作后调用该方法
     * 作用:提示操作成功
     */
    @After(value = "execution(* com.stt.service.UserService.addUser(..)) || " +
            " execution(* com.stt.service.UserService.updateUser(..)) || " +
            " execution(* com.stt.service.UserService.deleteUser(..))")
    public void success(){
        System.out.println("操作成功");
    }
}

2.4.3、applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!--开启注解扫描-->
    <context:component-scan base-package="com.stt"/>
    <!--开启aop操作-->
    <aop:aspectj-autoproxy/>

</beans>

2.4.4、测试

在这里插入图片描述

三、AOP原理

3.1、概述

 AOP的实现方式其实是代理模式,代理模式是给某一个对象提供一个代理对象,并由代理对象控制对原对象的引用。通俗的来讲代理模式就是我们生活中常见的中介。代理模式分为静态代理动态代理。静态代理是由程序员创建或特定工具自动生成源代码,再对其编译。在程序运行之前,代理类.class文件就已经被创建了。动态代理是在程序运行时通过反射机制动态创建的。

3.2、为什么使用代理模式

中介隔离作用:在某些情况下,一个客户类不想或者不能直接引用一个委托对象,而代理类对象可以在客户类和委托对象之间起到中介的作用,其特征是代理类和委托类实现相同的接口。
开闭原则,增加功能:代理类除了是客户类和委托类的中介之外,我们还可以通过给代理类增加额外的功能来扩展委托类的功能,这样做我们只需要修改代理类而不需要再修改委托类,符合代码设计的开闭原则。代理类主要负责为委托类预处理消息、过滤消息、把消息转发给委托类,以及事后对返回结果的处理等。代理类本身并不真正实现服务,而是同过调用委托类的相关方法,来提供特定的服务。真正的业务功能还是由委托类来实现,但是可以在业务功能执行的前后加入一些公共的服务。例如我们想给项目加入缓存、日志这些功能,我们就可以使用代理类来完成,而没必要打开已经封装好的委托类。

3.3、静态代理

3.3.1、接口

package com.stt.service;

/**
 * 定义接口
 */
public interface IPersonService {
    void speak();
}

3.3.2、实现类

package com.stt.service.impl;

import com.stt.service.IPersonService;

/**
实现类
 */
public class PersonService implements IPersonService {

    public void speak() {
        System.out.println("君不见,高堂明镜悲白发,朝如青丝暮成雪。");
    }
}

3.3.3、代理对象

package com.stt.service.impl;

import com.stt.service.IPersonService;

/**
 * ClassName: PersonServiceProxy
 * Description:
 * date: 2019/10/17 0017 下午 20:31
 *
 * @author stt
 * @since JDK 1.8
 */
public class PersonServiceProxy implements IPersonService {
    private IPersonService personService;
    public PersonServiceProxy(final IPersonService personService){
        this.personService = personService;
    }
    public void speak() {
        System.out.println("君不见,黄河之水天上来,奔流到海不复回。");
        personService.speak();
        System.out.println("人生得意须尽欢,莫使金樽空对月。\n" +
                "天生我材必有用,千金散尽还复来。\n" +
                "烹羊宰牛且为乐,会须一饮三百杯。\n" +
                "岑夫子,丹丘生,将进酒,杯莫停。\n" +
                "与君歌一曲,请君为我倾耳听。(倾耳听 一作:侧耳听)\n" +
                "钟鼓馔玉不足贵,但愿长醉不复醒。(不足贵 一作:何足贵;不复醒 一作:不愿醒/不用醒)\n" +
                "古来圣贤皆寂寞,惟有饮者留其名。(古来 一作:自古;惟 通:唯)\n" +
                "陈王昔时宴平乐,斗酒十千恣欢谑。\n" +
                "主人何为言少钱,径须沽取对君酌。\n" +
                "五花马,千金裘,呼儿将出换美酒,与尔同销万古愁。");
    }
}

3.3.4、测试

package com.stt.test;

import com.stt.pojo.Person;
import com.stt.service.UserService;
import com.stt.service.impl.PersonService;
import com.stt.service.impl.PersonServiceProxy;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * ClassName: SpringTest
 */
public class SpringTest {
    public static void main(String[] args) {
        //创建PersonService对象
        PersonService personService = new PersonService();
        personService.speak();
        //创建代理对象
        PersonServiceProxy personServiceProxy = new PersonServiceProxy(personService);
        personServiceProxy.speak();
    }
}

3.3.5、静态代理总结

 优点:可以做到在符合开闭原则的情况下对目标对象进行功能扩展。

 缺点:我们得为每一个服务都得创建代理类,工作量太大,不易管理。同时接口一旦发生改变,代理类也得相应修改。

3.4、动态代理

3.4.1、特点

 1、不需要生成实现接口
 2、使用JDK的API在内存中构建代理对象

3.4.2、代理类

package com.stt.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * PersonService代理对象
 */
public class PersonServiceProxy implements InvocationHandler {
    //业务类对象
    private Object target;

    public PersonServiceProxy(Object target){
        this.target = target;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object result = null;
        System.out.println("invoke开始");
        result = method.invoke(target,args);
        System.out.println("invoke结束");
        return result;
    }
}

3.4.3、测试

package com.stt.test;

import com.stt.pojo.Person;
import com.stt.proxy.PersonServiceProxy;
import com.stt.service.IPersonService;
import com.stt.service.UserService;
import com.stt.service.impl.PersonService;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.lang.reflect.Proxy;

/**
 * ClassName: SpringTest
 */
public class SpringTest {
    public static void main(String[] args) {
        //被代理对象
        PersonService personService = new PersonService();
        //代理对象
        PersonServiceProxy serviceProxy = new PersonServiceProxy(personService);
        //获取类加载器
        ClassLoader classLoader = personService.getClass().getClassLoader();
        //获取该类的接口
        Class<?>[] interfaces = personService.getClass().getInterfaces();
        IPersonService iPersonService = (IPersonService)Proxy.newProxyInstance(classLoader, interfaces, serviceProxy);
        iPersonService.speak();
    }
}

3.4.4、总结

 1、实现InvocationHandler接口重写invoke方法
 2、创建代理对象使用Proxy类的newProxyInstance方法,传入实现类类加载器,接口和代理类的对象
求知并无捷径,如果有,那就是放弃这个幼稚的想法,静下心来多读书、总结,希望对大家有所帮助

发布了23 篇原创文章 · 获赞 49 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_36386908/article/details/102589036