关于SpringAOP的三种实现方式你有了解过吗?——(开袋即食篇)

SpringAOP的三种实现方式


原文地址
原文地址
原文地址

Aop的基本概念

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

我的理解总的一句话就是没有侵入性的为原先的应用提供方法增强或者是补充。

AOP的几个关键词

1.Aspect(切面):通常是一个类,里面可以定义切入点(LogAspect)和通知(doBefore())

2.JointPoint(连接点):程序执行过程中明确的点,一般是方法的调用如index(),addUser();

3.Advice(通知):AOP在特定的切入点上执行的增强处理,就是你使用Aop的目的,如记录日志等,有before,after,afterReturning,afterThrowing,around

4.Pointcut(切入点):就是带有通知的连接点,在程序中主要体现为书写切入点表达式如@Pointcut(“execution(public * com.he.controller..(…))”)

5.AOP代理:AOP框架创建的对象,代理就是目标对象的加强。Spring中的AOP代理可以使JDK动态代理,也可以是CGLIB代理,前者基于接口,后者基于子类

首先的准备工作

​ 准备:首先我们要在maven中引入所需要的jar包。我们假设我们需要为我们的某个接口下的所有方法添加日志功能, 那么需要一个service接口和对应的实现类。

 	<dependency>
         <groupId>org.aspectj</groupId>
         <artifactId>aspectjweaver</artifactId>
         <version>1.9.4</version>
     </dependency>
public interface UserService {
    public int add(int num);
    public void delete();
    public void update();
    public void select();
}
public class UserServiceImpl implements UserService {
    public int add(int num) {
        System.out.println("添加了"+num+"个用户");
        return 1;//假设我们添加成功后会返回结果1。
    }
    public void delete() {
        System.out.println("删除了一个用户");
    }
    public void update() {
        System.out.println("更新了一个用户");
    }
    public void select() {
        System.out.println("查询了一个用户");
    }
}

方式一:使用spring的API接口

      步骤一:spring自身提供了对应的接口,我们只需要实现相应的接口就可以

在这里插入图片描述

       步骤二:编写对应的实现类分别继承spring-aop包下的MethodBeforeAdvice接口和AfterReturningAdvice接口

public class BeforeLog implements MethodBeforeAdvice {
    //方法执行前
    public void before(Method method, Object[] args, Object target){
        System.out.println("被代理对象->"+target.getClass().getName());
        System.out.println("执行方法->"+method.getName());
        System.out.println("执行方法的参数->"+args[0]);
        System.out.println("******方法执行前*******");
    }
}
public class AfterLog implements AfterReturningAdvice {
    //方法执行完成后
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target){
        System.out.println("******方法执行完成后*******");
        System.out.println("被代理的对象->"+target.getClass().getName());
        System.out.println("执行方法->"+method.getName());
        System.out.println("执行方法的参数->"+args[0]);
        System.out.println("返回结果->"+returnValue);
    }
}

       步骤三:注册编写的实现类到spring

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">
    <!--注册bean-->
  	<bean id="userService" class="com.he.service.UserServiceImpl"/>
    <bean id="beforeLog" class="com.he.log.BeforeLog"/>
    <bean id="afterLog" class="com.he.log.AfterLog"/>

		<!--方式一:使用原生Spring API接口-->
        <aop:config>
            <!--切入点:expression 表达式:execution(返回类型 包名.所有方法名(所有参数))-->
            <aop:pointcut id="pointcut" expression="execution(* com.he.service.UserServiceImpl.*(..))"/>
        <!--配置环绕方法类-->
            <aop:advisor advice-ref="beforeLog" pointcut-ref="pointcut"/>
            <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
        </aop:config>
</beans>

      步骤四:测试

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = (UserService) context.getBean("userService");
        userService.add(100);
    }
}
//返回结果
//被代理对象->com.he.service.UserServiceImpl
//执行方法->add
//执行方法的参数->100
//******方法执行前*******
//添加了100个用户
//******方法执行完成后*******
//被代理的对象->com.he.service.UserServiceImpl
//执行方法->add
//执行方法的参数->100
//返回结果->1

方式二:自定义类

      步骤一:自定义通知方法

public class MyPointCut {
    public void Before() {
        System.out.println("方法执行前");
    }
    public void After() {
        System.out.println("方法执行后");
    }
    public void AfterThrowing(){
        System.out.println("发生异常");
    }
}

       步骤二:注册自定义类MyPointCut进spring,配置通知方法

	<!--方式二:自定义类-->
    <bean id="diy" class="com.he.mypointcut.MyPointCut"/>
    <aop:config>
        <!--自定义切面,pointcut-ref引用切入点-->
        <aop:aspect ref="diy">
            <!--切入点-->
            <aop:pointcut id="point" expression="execution(* com.he.service.UserServiceImpl.*(..))"/>
            <!--通知方法-->
            <aop:before method="Before" pointcut-ref="point"/>
            <aop:after method="After" pointcut-ref="point"/>
            <aop:after-throwing method="AfterThrowing" pointcut-ref="point"/>
            <!--<aop:after-returning method="AfterReturning" pointcut-ref="point"/>-->
        </aop:aspect>
    </aop:config>

       步骤三:测试,这里我先在add方法中创造出一个异常->int x=1/0;

public class UserServiceImpl implements UserService {
    public int add(int num) {
        System.out.println("添加了"+num+"个用户");
        int x=1/0;
        return 1;//假设我们添加成功后会返回结果1。
    }
    public void delete() {
        System.out.println("删除了一个用户");
    }
    public void update() {
        System.out.println("更新了一个用户");
    }
    public void select() {
        System.out.println("查询了一个用户");
    }
}
public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = (UserService) context.getBean("userService");
        userService.add(100);
    }
}
//方法执行前
//添加了100个用户
//方法执行后
//发生异常
//Exception in thread "main" java.lang.ArithmeticException: / by zero

方式三:使用注解实现

      步骤一:定义切面类

@Aspect         //定义切面加上Aspect注解
public class AnnotationPointCut {
    @Before( "execution(* com.he.service.UserServiceImpl.*(..))")
    public void before() {
        System.out.println("方法执行前,注解实现");
    }

    @After( "execution(* com.he.service.UserServiceImpl.*(..))")
    public void after() {
        System.out.println("方法执行后,注解实现");
    }

//在环绕增强时我们在注解中声明切入点
    @Around( "execution(* com.he.service.UserServiceImpl.*(..))")
    public Object around(ProceedingJoinPoint jp) throws Throwable {
        System.out.println("环绕前");
        Signature signature=jp.getSignature();
        System.out.println("signature:"+signature);
        Object proceed = jp.proceed();     //相当于执行本来的方法
        System.out.println("环绕后");
        System.out.println(proceed);
        return proceed;
    }
}

      步骤二:在spring中注册并配置

   <!--方式三-->
    <bean id="annotationPointCut" class="com.he.mypointcut.AnnotationPointCut"/>
    <!--开启注解支持-->
    <aop:aspectj-autoproxy proxy-target-class="false"/><!--默认false JDK接口代理  true:cglib基于类的代理-->

      步骤三:测试

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = (UserService) context.getBean("userService");
        userService.add(100);
    }
}
//环绕前
//执行的方法->int com.he.service.UserService.add(int)
//方法执行前,注解实现
//添加了100个用户
//环绕后
//返回值->1
//方法执行后,注解实现

总结:

      SpringAOP是对动态代理模式一个很好的实践,并且全部的实现都交给spring来做,简化了开发的工作,最主要降低了程序的各部分之间的耦合度,提高程序的可重用性。在实际拿到开发任务总不会为了实现新功能去动原来的业务代码吧,而Spring天生的AOP特性就很好的解决了这一点。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值