方法前调用指定方法

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 BeforeMethod {
    String methodName();

}


import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;

/**
 * @Description: 调用方法前调用
 * @DateTime: 2023/8/19 14:22
 */
@Aspect
@Component
public class BeforeMethodAOP {

    @Resource
    private ApplicationContext applicationContext;

    @Before(value = "@annotation(com.ruijie.common.core.annotation.BeforeMethod)")
    public void before(JoinPoint joinPoint) {
        String methodName = "";
        Method method1 = null;
        try {
            MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
            Method method = methodSignature.getMethod();
            BeforeMethod beforeMethodAnnotation = method.getAnnotation(BeforeMethod.class);
            methodName = beforeMethodAnnotation.methodName();
            Class<?> targetClass = joinPoint.getTarget().getClass();
            method1 = targetClass.getMethod(methodName);
            // 创建目标类的实例(如果需要调用的方法是非静态方法)
            Object targetObject = targetClass.newInstance();
            Object bean = applicationContext.getBean(targetObject.getClass());
            method1.invoke(bean);
        } catch (Exception e) {
            throw new BusinessException("Call failed-" + method1.toString());
        }
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值