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());
}
}
}