前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spring-AOP思想

Spring-AOP思想

作者头像
Java开发者之家
发布2021-06-17 16:49:02
2460
发布2021-06-17 16:49:02
举报
文章被收录于专栏:Java开发者之家Java开发者之家

# Spring AOP

# 使用动态代理实现aop
代码语言:javascript
复制
package top.finen.spring.aop.helloworld;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

public class ArithmeticCalculatorLoggingProxy {
    private ArithmeticCalculator target;

    public ArithmeticCalculatorLoggingProxy(ArithmeticCalculator target) {
        this.target = target;
    }

    public ArithmeticCalculator getLoggingProxy() {
       ArithmeticCalculator arithmeticCalculator = null;
       //代理对象有那一个类加载器加载
       ClassLoader loader = target.getClass().getClassLoader();
       //代理对象的类型,即其中有那些方法
       Class[] interfaces = new Class[]{ArithmeticCalculator.class};
       //当调用代理对象其中的方法时,该执行的代码
       InvocationHandler handler = new InvocationHandler() {
           /**
            *
            * @param proxy 正在返回的那个代理对象,一般情况下,在invoke方法中都不使用该对象。
            * @param method 正在被调用的方法
            * @param args 方法调用时,传入的参数
            * @return
            * @throws Throwable
            */
           @Override
           public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
               String methodName = method.getName();
               //日志
               System.out.println("The method " + methodName + " begin with " + Arrays.asList(args));

               Object result = null;
               //返回方法
               try {
                   //前置通知
                   result = method.invoke(target, args);
                   //返回通知:可以访问到方法的返回值
               } catch (Exception e) {
                   e.printStackTrace();
                   //异常通知
               }

               //后置通知:因为方法可能出现异常,所以访问不到方法的返回值

               //日志
               System.out.println("The method " + methodName + " ends with " + result);
               return result;
           }
       };
       arithmeticCalculator = (ArithmeticCalculator) Proxy.newProxyInstance(loader, interfaces, handler);
       return arithmeticCalculator;
    }
}
代码语言:javascript
复制
public class Main {
    public static void main(String[] args) {
        ArithmeticCalculator target = new ArithmeticCalculatorImpl();
        ArithmeticCalculator proxy = new ArithmeticCalculatorLoggingProxy(target).getLoggingProxy();
        int result = proxy.add(1, 2);
        System.out.println("------" + result);
    }
}
# AOP思想
  • AOP的主要编程对象是切面,而切面模块化横切关注点。
  • 在应用AOP编程时,任然需要定义公共功能,但可以明确的定义这个在哪里,以什么方式应用,并且不必修改手影响的类。这样横切关注点就被模块化到特殊的对象(切面中)。
  • AOP好处
    • 每个事物逻辑位于一个位置,代码不分散,便于维护和升级。
    • 业务模块更简洁,只包含核心页面代码。
# AOP关键术语
  • 切面:横切关注点被模块化的特殊对象。
  • 通知:切面必须完成的工作。
  • 目标:被通知的对象。
  • 连接点(Joinpoint): 程序执行的某个特定位置。如果某方法调用前,调用后,方法抛出异常后。连接点由两个 信息确定:方法表示的程序执行点;相对点表示的方位。
  • 切点: 每个类都拥有多个连接点。AOP通过切点定位到特定的连接点。类比:连接点相当于数据库中的记录。切点相当于查询条件。
# Spring AOP

加入Jar包 com.springsource.org.aopalliance-1.0.0.jar com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar spring-aop-4.3.18.RELEASE.jar spring-aspects-4.3.18.RELEASE.jar

commons-logging-1.1.1.jar spring-beans-4.3.18.RELEASE.jar spring-context-4.3.18.RELEASE.jar spring-core-4.3.18.RELEASE.jar spring-expression-4.3.18.RELEASE.jar

在配置文件中加入aop的命名空间

基于注解的方式

代码语言:javascript
复制
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

把横切关注点的代码抽象到切面的类中。

1.切面首先是一个IOC的bean,即加入@Component注解 2.切面还需要加入@Aspect注解

在类中声明各种通知:

1.声明一个方法

2.在方法前加入@Before注解

代码语言:javascript
复制
@Before("execution(public int top.finen.spring.aop.impl.ArithmeticCalculator.*(int, int))")

1

可以在声明的通知方法中声明一个类型为JoinPoint的参数,然后就能访问链接细节,如方法名称和参数。

代码语言:javascript
复制
@Aspect
@Component
public class LoggingAspect {

    //声明该方法是一个前置通知:在目标方法之前执行
    @Before("execution(public int top.finen.spring.aop.impl.ArithmeticCalculator.*(int, int))")
    public void beforeMethod(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        List<Object> args = Arrays.asList(joinPoint.getArgs());
        System.out.println("The method " + methodName + " begins with:" + args);
    }
}
# SpringAOP的5种通知-基于注解方法
代码语言:javascript
复制
package top.finen.spring.aop.impl;


import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * @author finen
 * 把这个类声明为一个切面:需要把该类放入到IOC容器中,在声明为一个切面
 * 可以使@Order注解指定切面优先级,优先级值越小优先级越高
 */
@Order(2)
@Aspect
@Component
public class LoggingAspect {

    /**
     * 定义一个方法:用于声明切入点表达式,一般地,该方法中不需要切入其他的的代码
     * 使用@Pointcut来声明切入点表达式
     * 后面的其他通知直接使用方法名引用当前切入点表达式
     */
    @Pointcut("execution(public int top.finen.spring.aop.impl.ArithmeticCalculator.*(int, int))")
    public void declareJoinPointExpression() {}

    /**
     * 声明该方法是一个前置通知:在目标方法之前执行
     * 在声明能获取到执行的参数
     * @param joinPoint
     */
    @Before("declareJoinPointExpression()")
    public void beforeMethod(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        List<Object> args = Arrays.asList(joinPoint.getArgs());
        System.out.println("The method " + methodName + " begins with:" + args);
    }

    /**
     * 后置通知:在目标方法执行后(无论是否发生异常),执行的通知
     * 在后置通知中还不能访问目标方法执行的结果。
     * @param joinPoint
     */
    @After("declareJoinPointExpression()")
    public void afterMethod(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        System.out.println("The method " + methodName + " end");

    }

    /**
     * 在方法结束受执行代码的之后返回的通知
     * 返回通知是可以访问到方法的返回值的
     * @param joinPoint
     */
    @AfterReturning(value = "declareJoinPointExpression()",
            returning = "result")
    public void afterReturning(JoinPoint joinPoint, Object result) {
        String methodName = joinPoint.getSignature().getName();
        System.out.println("The method " + methodName + " end with: " + result);

    }

    /**
     * 在方法出现异常时,会执行的代码
     * 可以访问到异常对象,且可以指定出现特定异常时在执行通知代码。
     * @param joinPoint
     * @param exception
     */
    @AfterThrowing(value = "declareJoinPointExpression()",
            throwing = "exception")
    public void afterThrowing(JoinPoint joinPoint, Exception exception) {
        String methodName = joinPoint.getSignature().getName();
        System.out.println("The method " + methodName + " throwing with: " + exception);
    }

    /**
     * 环绕通知需要携带ProceedingJoinPoint类型的参数
     * 环绕通知类似于动态代理的全过程:ProceedingJoinPoint类型的参数可以决定是否执行目标方法
     * 环绕通知必须有返回值,且返回值为目标方法的返回值
     * @param proceedingJoinPoint
     */
    @Around("declareJoinPointExpression()")
    public Object aroundMethod(ProceedingJoinPoint proceedingJoinPoint) {

        Object result = null;
        String methodName = proceedingJoinPoint.getSignature().getName();

        //执行目标方法
        try {
            //前置通知
            System.out.println("The method " + methodName + " begins with:" + Arrays.asList(proceedingJoinPoint.getArgs()));
            result = proceedingJoinPoint.proceed();
            //返回通知
            System.out.println("The method " + methodName + " end with:" + result);
        } catch (Throwable throwable) {
            //异常通知
            System.out.println("The method " + methodName + " throwing with: " + throwable);
            throwable.printStackTrace();
        }
        //后置通知
        System.out.println("The method " + methodName + " end");
        return result;
    }
}
# Spring基于XML文件的方式配置AOP
代码语言:javascript
复制
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * @author finen
 * 把这个类声明为一个切面:需要把该类放入到IOC容器中,在声明为一个切面
 * 可以使@Order注解指定切面优先级,优先级值越小优先级越高
 */

public class LoggingAspect {


    public void declareJoinPointExpression() {}

    public void beforeMethod(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        List<Object> args = Arrays.asList(joinPoint.getArgs());
        System.out.println("The method " + methodName + " begins with:" + args);
    }

    public void afterMethod(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        System.out.println("The method " + methodName + " end");

    }


    public void afterReturning(JoinPoint joinPoint, Object result) {
        String methodName = joinPoint.getSignature().getName();
        System.out.println("The method " + methodName + " end with: " + result);

    }


    public void afterThrowing(JoinPoint joinPoint, Exception exception) {
        String methodName = joinPoint.getSignature().getName();
        System.out.println("The method " + methodName + " throwing with: " + exception);
    }
}
代码语言:javascript
复制
<?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-4.0.xsd">
    <!--配置bean-->
    <bean id="arithmeticCalculator" class="top.finen.spring.aop.xml.ArithmeticCalculatorImpl"></bean>

    <bean id="loggingAspect" class="top.finen.spring.aop.xml.LoggingAspect"></bean>

    <bean id="validationAspect" class="top.finen.spring.aop.xml.ValidationAspect"></bean>

    <!--配置AOP-->
    <aop:config>
        <aop:pointcut id="pointcut" expression="execution(* top.finen.spring.aop.xml.ArithmeticCalculator.*(int, int))"/>
        <!--配置切面以及配置-->
        <aop:aspect ref="loggingAspect" order="2">
            <aop:before method="beforeMethod" pointcut-ref="pointcut"></aop:before>
            <aop:after method="afterMethod" pointcut-ref="pointcut"></aop:after>
            <aop:after-throwing method="afterThrowing" pointcut-ref="pointcut" throwing="exception"></aop:after-throwing>
            <aop:after-returning method="afterReturning" pointcut-ref="pointcut" returning="result"></aop:after-returning>
        </aop:aspect>
        <aop:aspect ref="validationAspect" order="1">
            <aop:before method="validateArgs" pointcut-ref="pointcut"></aop:before>
        </aop:aspect>
    </aop:config>
</beans>
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-02-02 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • # Spring AOP
    • # 使用动态代理实现aop
      • # AOP思想
        • # AOP关键术语
          • # Spring AOP
            • # SpringAOP的5种通知-基于注解方法
              • # Spring基于XML文件的方式配置AOP
              相关产品与服务
              容器服务
              腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
              领券
              问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档