Spring之AOP(七)

Spring之AOP(七)

参考:Spring官方文档
微信公众号:狂神说

一、什么是AOP

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

简单的来说,一般我们的开发流程是纵向开发,dao—>service—>controller。 那么对于切面,就是我们要在service层增加比如日志功能,这时候我们怎么办?难道去修改源码增加代码吗?这样可能造成你增加了之后代码跑不起来。这时候就需要用代理来做,也就是我们这里的面向切面,横切进service层 去增加代理来实现新功能!

1.1 AOP在Spring中的作用

提供声明式事务;允许用户自定义切面

以下名词需要了解下:

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

二、Spring实现AOP

【重点】使用AOP,需要导入一个依赖包!

<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
   <groupId>org.aspectj</groupId>
   <artifactId>aspectjweaver</artifactId>
   <version>1.9.4</version>
</dependency>

2.1 方式一(通过Spring API)

编写我们的业务接口和实现类

public interface UserService {

   public void add();

   public void delete();

   public void update();

   public void search();

}

实现类

public class UserServiceImpl implements UserService{

   @Override
   public void add() {
       System.out.println("增加用户");
  }

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

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

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

然后去写我们的增强类 , 我们编写两个 , 一个前置增强 一个后置增强

public class Log implements MethodBeforeAdvice {
    /**
     * @param method 要执行的目标对象的方法
     * @param args 参数
     * @param target 目标对象
     * @throws Throwable
     */
    @Override
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
    }
}
public class AfterLog implements AfterReturningAdvice {
    /**
     *
     * @param returnValue 返回结果
     * @param method 要执行目标对象的方法
     * @param args  方法的参数
     * @param target 目标对象 注意是接口
     * @throws Throwable
     */
    @Override
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("执行了"+method.getName()+"返回结果为:"+returnValue);
    }
}

最后要在Spring配置文件中注册,实现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: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-->
    <bean id="userService" class="com.kuang.service.UserServiceImpl"/>
    <bean id="log" class="com.kuang.log.Log"/>
    <bean id="afterlog" class="com.kuang.log.AfterLog"/>

	<!--方式一-->
    <!--配置aop:导入aop的约束-->
    <aop:config>
        <!--切入点:在哪个地方执行aop
         expression:表达式
         execution(要执行的位置! * * * * *)
         如下的意思是这个包下的*任意方法的(..)任意参数
         -->
        <aop:pointcut id="pointcut" expression="execution(* com.kuang.service.UserServiceImpl.*(..))"/>

        <!--执行环绕增强-->
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterlog" pointcut-ref="pointcut"/>

    </aop:config>

</beans>

测试

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        //UserServiceImpl userService = applicationContext.getBean("userService", UserServiceImpl.class);
        //注意动态代理代理的是接口 这里一定是返回接口类型
        UserService userService = applicationContext.getBean("userService", UserService.class);
        userService.add();
    }
}

Aop的重要性 : 很重要 . 一定要理解其中的思路 , 主要是思想的理解这一块 .

Spring的Aop就是将公共的业务 (日志 , 安全等) 和领域业务结合起来 , 当执行领域业务时 , 将会把公共业务加进来 . 实现公共业务的重复利用 . 领域业务更纯粹 , 程序猿专注领域业务 , 其本质还是动态代理 .

2.2 方式二(使用自定义类)

自定义一个类,实际上在后面就是切面的意思

public class DiyPointCut {
    public void before(){
        System.out.println("===========方法执行前==============");
    }

    public void after(){
        System.out.println("*********方法执行后*********");
    }
}

配置文件,这里的切面和通知的意思就是文章开头所解释的名词。

	<!--方式二-->
    <bean id="diy" class="com.kuang.diy.DiyPointCut"/>

    <aop:config>
        <!--自定义切面,ref:要引用的类-->
        <aop:aspect ref="diy">
            <!--切入点-->
            <aop:pointcut id="point" expression="execution(* com.kuang.service.UserServiceImpl.*(..))"/>
            <!--通知-->
            <aop:before method="before" pointcut-ref="point"/>
            <aop:after method="after" pointcut-ref="point"/>
        </aop:aspect>
    </aop:config>

总结:

  • 方式二的便利在于创建切面类的时候,方式一需要实现MethodBeforeAdviceAfterReturningAdvice来确定切面类是前置通知还是后置通知
  • 在配置文件书写上也比较清晰,配置一个切面(类),内嵌标签中的通知就是类中的方法。

三、注解实现AOP

话不多说先上代码

//方式三:注解
@Aspect //标志该类为一个切面
public class AnnotationPoinCut {

    @Before("execution(* com.kuang.service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("===方法执行前");
    }

    @After("execution(* com.kuang.service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("方法执行后===");
    }

    //在环绕增强 可以给定一个参数,代表我们要获取切入的点
    @Around("execution(* com.kuang.service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint jp) throws Throwable {
        System.out.println("环绕前");

        System.out.println("signature:"+jp.getSignature());//获得签名
        //执行方法
        Object proceed = jp.proceed();

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

}
<!--方式三-->
    <bean id="annoAop" class="com.kuang.diy.AnnotationPoinCut"/>

    <!--开启注解支持! JDK(默认proxy-target-class="false") cglib-->
    <aop:aspectj-autoproxy proxy-target-class="false"/>

注意这里如果用@Component方式将该类设置为组件是不行的!!

必须在配置文件中注册bean,如果知道为什么请留言!!!感谢!!!

接下来解释

  • @Aspect 表示该类为切面(类)
  • @Before(xxx) 表示是前置方法
  • @After(xxx) 后置方法
  • @Around(xxx) 环绕增强 可以给一个参数 如public void around(ProceedingJoinPoint jp)中的参数

其中三个通知(前置/后置/环绕)注解都需要写切入点(也就是切入到什么方法。。。)

测试

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        //UserServiceImpl userService = applicationContext.getBean("userService", UserServiceImpl.class);
        //注意动态代理代理的是接口
        UserService userService = applicationContext.getBean("userService", UserService.class);
        userService.add();
    }
}

在这里插入图片描述

注意执行顺序

  1. 环绕中的先执行,然后执行了signature

  2. 然后执行前置通知

  3. 再执行方法,类似于invoke了userService的add()方法

  4. 后置通知

  5. 环绕结束

  6. 返回值

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值