使用自定义注解和Spring AOP实现前后置方法调用

使用自定义注解和Spring AOP实现前后置方法调用

在开发过程中,经常会遇到需要在方法执行前后添加一些逻辑的情况,例如记录日志、性能监控、事务管理等。使用Spring AOP(Aspect-Oriented Programming)和自定义注解,可以方便地实现这些需求。本文将详细介绍如何通过Java和Spring AOP实现一个自定义注解,用于在方法执行前后调用指定的函数。

1. 创建自定义注解

首先,我们创建一个自定义注解 @ExecuteFunctions,并增加一个 beforeParam 参数,用于传递给前置方法。注解的代码如下:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ExecuteFunctions {
    int beforeParam() default 0;
}

这个注解具有一个 beforeParam 参数,默认值为 0,它将用于传递一个整数值给前置方法。

2. 创建服务类

接下来,我们创建一个服务类 FunctionService,其中包含前置和后置方法。前置方法 functionBefore 接收一个整数参数,后置方法 functionAfter 不需要参数。

import org.springframework.stereotype.Service;

@Service
public class FunctionService {

    public void functionBefore(int param) {
        System.out.println("Function Before Execution with param: " + param);
    }

    public void functionAfter() {
        System.out.println("Function After Execution");
    }
}
3. 创建切面类

为了在方法执行前后调用指定的函数,我们需要创建一个切面类 FunctionAspect。这个类使用 @Aspect 注解定义一个切面,并使用 @Around 注解定义环绕通知,处理前置和后置函数的执行。

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class FunctionAspect {

    @Autowired
    private FunctionService functionService;

    @Pointcut("@annotation(executeFunctions)")
    public void executeFunctionsPointcut(ExecuteFunctions executeFunctions) {}

    @Around("executeFunctionsPointcut(executeFunctions)")
    public Object around(ProceedingJoinPoint joinPoint, ExecuteFunctions executeFunctions) throws Throwable {
        int beforeParam = executeFunctions.beforeParam();

        // 执行前置函数
        invokeFunction("functionBefore", beforeParam);

        Object result = null;
        try {
            // 执行目标方法
            result = joinPoint.proceed();
        } finally {
            // 执行后置函数
            invokeFunction("functionAfter");
        }

        return result;
    }

    private void invokeFunction(String functionName, int param) throws Exception {
        Method method = FunctionService.class.getMethod(functionName, int.class);
        method.invoke(functionService, param);
    }

    private void invokeFunction(String functionName) throws Exception {
        Method method = FunctionService.class.getMethod(functionName);
        method.invoke(functionService);
    }
}

FunctionAspect 类中,我们定义了一个 @Around 通知,用于在目标方法执行前后调用前置和后置方法。invokeFunction 方法通过反射调用带有参数或不带参数的方法。

4. 使用自定义注解

在需要执行前置和后置函数的方法上使用 @ExecuteFunctions 注解,并指定 beforeParam 参数。例如,在一个控制器类中使用这个注解:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DemoController {

    @Autowired
    private FunctionService functionService;

    @ExecuteFunctions(beforeParam = 42)
    @GetMapping("/test")
    public String test() {
        System.out.println("Executing target method");
        return "Hello, World!";
    }
}
5. 启动Spring Boot应用

确保你的Spring Boot应用正确配置并启动。访问 /test 路径,应该会看到如下输出:

Function Before Execution with param: 42
Executing target method
Function After Execution
解释
  1. 自定义注解

    • @ExecuteFunctions 注解增加了一个 beforeParam 参数,用于传递一个整数值给 functionBefore 方法。
  2. 服务类

    • FunctionService 定义了带有 int 参数的 functionBefore 方法和无参数的 functionAfter 方法。
  3. 切面类

    • FunctionAspect 类使用 @Aspect 注解定义一个切面,使用 @Around 注解定义了环绕通知,处理前置和后置函数的执行。
    • invokeFunction 方法通过反射调用带有 int 参数的 functionBefore 方法,并在方法参数不为空时传递参数。
  4. 控制器

    • DemoController 类中,使用 @ExecuteFunctions 注解标注需要执行前置和后置函数的方法,并指定 beforeParam 参数。

通过这种方式,我们实现了一个灵活的解决方案,可以在方法执行前后调用指定的函数,并且支持通过注解参数传递值给前置函数。这样的实现不仅提高了代码的可读性和可维护性,还增强了代码的扩展性和复用性。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值