美文网首页
AOP代码实战

AOP代码实战

作者: smallwhite_wind | 来源:发表于2024-01-05 21:55 被阅读0次

AOP(面向划面编程)是一种编程范式,旨在提高代码的模块化。它允许开发者将横切关注点(cross-cutting concerns),如日志记录、事务管理、安全性等,从他们影响的业务逻辑中分离出来。在Java世界中,Spring框架是实现AOP最常见的工具之一。

以下是一个简单的AOP示例,其中定义了一个切面(Aspect)来织入日志记录的行为:


import org.aspectj.lang.annotation.Aspect;

import org.aspectj.lang.annotation.Before;

import org.aspectj.lang.annotation.Pointcut;

import org.aspectj.lang.JoinPoint;

import org.springframework.stereotype.Component;

@Aspect

@Component

public class LoggingAspect {

    // 定义一个切入点,匹配所有Service类的方法

    @Pointcut("within(com.example.service.*)")

    public void serviceMethods() {

    }

    // 在每个服务方法之前执行

    @Before("serviceMethods()")

    public void logMethodAccessBefore(JoinPoint joinPoint) {

        String methodName = joinPoint.getSignature().getName();

        System.out.println("Before running loggingAdvice on method=" + methodName);

    }

    // 你可以添加更多的通知(Advice),例如After, AfterReturning, AfterThrowing, Around等

}


在上述代码中,`@Aspect`注解标记了`LoggingAspect`类作为一个切面。`@Pointcut`注解定义了一个名为`serviceMethods`的切点,它匹配位于`com.example.service`包下任意类的所有方法。`@Before`注解表明了`logMethodAccessBefore`方法应该在匹配切点的方法之前执行。这样,每当调用服务层的任何方法时,都会先执行日志记录的逻辑。

为了使这个切面生效,你需要确保Spring AOP的相关配置已经设置好,并且在Spring容器中包含了`LoggingAspect`类。通常,这可以通过组件扫描完成,只要`LoggingAspect`类所在的包在Spring的组件扫描路径中即可。


AOP(面向方面编程)错误处理时,假设在Java中使用Spring框架的AspectJ注解来创建一个切面,该切面拦截方法执行并提供统一的异常处理。以下是一个简单的例子。

首先,定义一个自定义异常:


public class CustomException extends Exception {

    public CustomException(String message) {

        super(message);

    }

}

然后,创建一个示例服务,其中有可能抛出异常的方法:

import org.springframework.stereotype.Service;

@Service

public class ExampleService {

    public void someMethod() throws CustomException {

        // 模拟业务逻辑

        if (Math.random() > 0.5) {

            throw new CustomException("随机失败");

        }

    }

}

接下来,定义一个Aspect用于捕获`CustomException并进行处理:


import org.aspectj.lang.annotation.Aspect;

import org.aspectj.lang.annotation.AfterThrowing;

import org.springframework.stereotype.Component;

@Aspect

@Component

public class ErrorHandlingAspect {

    @AfterThrowing(pointcut = "execution(* com.yourpackage.ExampleService.*(..))", throwing = "ex")

    public void handleCustomException(CustomException ex) {

        // 处理异常, 比如记录日志或者执行其他错误处理逻辑

        System.out.println("发生了自定义异常: " + ex.getMessage());

    }

}

确保启动类上添加了@EnableAspectJAutoProxy注解,以便启用AOP代理支持:


import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.context.annotation.EnableAspectJAutoProxy;

@SpringBootApplication

@EnableAspectJAutoProxy

public class YourApplication {

    public static void main(String[] args) {

        SpringApplication.run(YourApplication.class, args);

    }

}

现在,当`ExampleService`的`someMethod`方法抛出`CustomException`时,`ErrorHandlingAspect`的`handleCustomException`方法会被自动调用,并能处理这个异常。

相关文章

  • AOP之AspectJ - 代码注入

    AOP之AspectJ - 代码注入 [TOC] 一、AOP简介 1.1 什么是AOP编程 AOP是Aspect ...

  • Spring之AOP详解(非原创)

    文章大纲 一、AOP介绍二、Spring的AOP实战三、AOP常用标签四、项目源码及参考资料下载五、参考文章 一、...

  • 面向切面编程AOP

    安卓 AOP 实战:面向切片编程 T-MVP

  • 架构师JavaEE高级知识点,符合您的口味,成就您的未来!

    SSM项目整合 Spring IOC AOP 底层原理与实战、Spring mvc 各大组件 实现原理与项目实战、...

  • AOP实战

    想用AOP做一个缓存。虽然看起来简单,但真正做完还是有些收获。 读操作不能每次都查询,所以需要缓存。先看下基础类 ...

  • 2019-06-11

    四、Spring的AOP AOP实现可分为两类(按AOP框架修改源代码的时机): 静态AOP实现:AOP框架在编译...

  • Spring的AOP

    、Spring的AOP AOP实现可分为两类(按AOP框架修改源代码的时机): 静态AOP实现:AOP框架在编译阶...

  • 动态AOP

    动态AOP 上篇文章我们讲到,AOP分为静态AOP和动态AOP。静态AOP在代码编译之后,已经有代理类或者已经改变...

  • 彻底征服 Spring AOP 之 实战篇

    接上一小节彻底征服 Spring AOP 之 理论篇 Spring AOP 实战 看了上面这么多的理论知识, 不知...

  • MYSQL读写分离核心方案代码

    此博客mysql的读写分离方案核心采用AOP,直接看核心代码。 1.AOP段的代码 @Component @Asp...

网友评论

      本文标题:AOP代码实战

      本文链接:https://www.haomeiwen.com/subject/xtwindtx.html