目录
代理
(帮别人做事情),在执行真正的任务之间或者之后,去完成某些事情。
比如日志,权限验证
1、静态代理:手动创建代理类
2、动态代理:自动创建代理类
实现技术:Jdk的动态代理(企业高频面试题),Cglib的动态代理
AOP的实现,利用的是动态代理技术
基于XML的AOP配置
首先需要引入Spring核心依赖
1、maven引入依赖(在pom.xml文件中引入)
<!--    aop依赖的jar -->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjtools</artifactId>
      <version>1.9.5</version>
    </dependency> 
 

2、创建Spring-aop.xml 文件并引入aop命名空间
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       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/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">
   
</beans> 
 

3、配置扫描的包(创建被代理的包)
<!--    扫描需要被代理的实现类-->
<context:component-scan base-package="com.gxa.dao.impl"></context:component-scan> 
 

4、创建切面类
package com.gxa.aop;
import org.springframework.stereotype.Component;
//切面类
@Component
public class MyAdvice {
    //前置通知
    public void beforeAdvice(){
        System.out.println("前置通知");
    }
    //后置通知
    public void afterAdvice(){
        System.out.println("后置通知");
    }
    //最后通知
    //异常通知
    //环绕通知
} 
 

5、扫描切面类
<!--    扫描切面类-->
    <context:component-scan base-package="com.gxa.aop"/> 
 

6、将切面类和实现类进行关联
<!--    AOP配置-->
<aop:config>
  <!--配置的代码写在这里-->
  <aop:aspect id="myAdvice" ref="myAdvice">
    <!--            配置切入点:告诉我们那些类的那些方法需要被增强-->
    <aop:pointcut id="myPoint" expression="execution(public void com.gxa.dao.impl.*.*(..))"/>
    <aop:before method="beforeAdvice" pointcut-ref="myPoint"></aop:before>
  </aop:aspect>
</aop:config> 
 

这样就完成了通过xml实现aop功能了
基于注解的AOP配置
1、切面类中加入注解:@Aspect
package com.gxa.aop;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
//切面类
@Component
    //1. 使用注解
    @Aspect
    public class MyAdvice {
        //2. 切入点
        @Pointcut("execution(public void com.gxa.dao.impl.*.*(..))")
        public void pointCut(){
        }
        //前置通知
        //3. 配置增强
        @Before(value = "pointCut()")
        public void beforeAdvice(){
            System.out.println("前置通知");
        }
        //后置通知
        public void afterAdvice(){
            System.out.println("后置通知");
        }
        //最后通知
        //异常通知
        //环绕通知
    } 
 

2、在xml文件中开启注解扫描

这样就可以实现aop功能了
Spring 的AOP实现默认使用JDK的动态代理
JDK的动态代理,代理类和被代理类(实现类)需要实现相同的接口









