[Transfer] Spring AOP intercepts classes or methods with specified annotation identifiers
Instructions for scanning specific annotations in AOP:
(1) @annotation: intercepts all methods annotated with the target annotation.
(2) @within: intercepts all classes annotated with the target annotation.
(3) within: limits the package scope to scan.
Code Demo
@Aspect
@Component
@Order(10)
public class BidAuthorityProxy {
/**
* Scan classes under the specified package that are annotated with `@EnableRoleAuthority`.
*/
@Around("@within(com.core.annotation.EnableRoleAuthority) && within(com.bid..*)")
public Object verifyRoleExecuteCommand(ProceedingJoinPoint pjp) throws Throwable {
// Get the intercepted method
MethodSignature msig = (MethodSignature) pjp.getSignature();
Method targetMethod = pjp.getTarget().getClass().getDeclaredMethod(msig.getName(), msig.getMethod().getParameterTypes());
// Read the annotation from the current method
VerifyRoleAuthority annotation = targetMethod.getAnnotation(VerifyRoleAuthority.class);
// If the class has no annotation, check the method on each implemented interface
if (annotation == null) {
Class<?>[] inters = pjp.getTarget().getClass().getInterfaces();
for (Class<?> inter : inters) {
Method targetInterMethod = inter.getDeclaredMethod(msig.getName(), msig.getMethod().getParameterTypes());
annotation = targetInterMethod.getAnnotation(VerifyRoleAuthority.class);
if (annotation != null) {
break;
}
}
}
// Apply custom logic after retrieving the annotation value
return pjp.proceed(); // Execute the method
}
}
Source
https://blog.csdn.net/java_faep/article/details/104005399