AOP

156 阅读2分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动

简介

什么是AOP?

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

上面是比较专业的术语概括,理解起来可能是比较麻烦的,想要理解切面编程,最想需要理解的概念就是什么叫切面;如果我们把一个对象看作整体,那对象与对象之间就相当于一个切面,也可以是模块与模块之间

作用:在程序运行期间,在不修改源码的情况下对方法进行功能增强;

优势:减少重复代码,提高开发效率,并且便于维护;

实际上,AOP 的底层是通过 Spring 提供的的动态代理技术实现的。在运行期间,Spring通过动态代理技术动态的生成代理对象,代理对象方法执行时进行增强功能的介入,在去调用目标对象的方法,从而完成功能的增强。

JDK 代理 : 基于接口的动态代理技术

cglib 代理:基于父类的动态代理技术

AOP开发流程

/**
导入AOP相关的坐标
*/
<!--导入spring的context坐标,context依赖aop-->
		<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.5.RELEASE</version>
        </dependency>
<!-- aspectj的织入 -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.4</version>
        </dependency>
 
    
/**
创建目标接口和目标类(内部有切点)
*/ 
//目标接口
public interface TargetInterface {
    public void save();
}
//目标类
public class Target implements TargetInterface {
    public void save() {
        System.out.println("save running.....");
    }
}

/**
创建切面类(内部有增强方法)
*/
public class MyAspect {
    //前置增强方法
    public void before(){
        System.out.println("前置代码增强.....");
    }
}

XML版本

/**
将目标类和切面类的对象创建权交给 spring
*/
<!--配置目标类-->
<bean id="target" class="com.qinli.aop.Target"></bean>
<!--配置切面类-->
<bean id="myAspect" class="com.qinli.aop.MyAspect"></bean>

/**
在 applicationContext.xml 中配置织入关系
*/
//导入命名空间
xmlns:aop="http://www.springframework.org/schema/aop"
    
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd

/**
在 applicationContext.xml 中配置织入关系
*/
<aop:config>
	<!--引用myAspect的Bean为切面对象-->
    <aop:aspect ref="myAspect">
    	<!--配置Target的method方法执行时要进行myAspect的before方法前置增强-->
        <aop:before method="before" pointcut="execution(public void com.qinli.aop.Target.method())"></aop:before>
    </aop:aspect>
</aop:config>

注解版本

/**
将目标类和切面类的对象创建权交给 spring
*/
@Component("target")
public class Target implements TargetInterface {
    @Override    public void method() {
        System.out.println("Target running....");
    }
}

@Component("myAspect")
public class MyAspect {
    public void before(){
        System.out.println("前置代码增强.....");
    }
}

/**
在切面类中使用注解配置织入关系
*/
@Component("myAspect")
@Aspect
public class MyAspect {
    @Before("execution(* com.itheima.aop.*.*(..))")
    public void before(){
        System.out.println("前置代码增强.....");
    }
}

/**
在配置文件中开启组件扫描和 AOP 的自动代理
*/
<!--组件扫描-->
    <context:component-scan base-package="com.qinli.aop"/>
<!--aop的自动代理-->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>