如何包装注释并将其有条件地应用于方法
How to wrap an annotation and conditionally applies it to a method
假设我在另一个库中引入了一个注解 (@RequiresAccount),我在我的项目中使用了它,有没有办法有条件地将它应用到一个方法中,例如当客户来自A网站时应用它,当客户来自B网站时不应用?
我已经看了一下,我发现的唯一可能是创建包装器注释:
@Aspect
@Component
public class RequiresAccountWrapperAspect {
@Autowired
private HttpServletRequest request;
private RequiresAccountAspect requiresAccountAspect = new RequiresAccountAspect();
@Around("@annotation(com.example.demo.components.RequiresAccountWrapper)")
public Object checkIfRequiresAccount(ProceedingJoinPoint joinPoint) throws Throwable {
String requestURL = request.getRequestURL().toString();
if (requestURL.startsWith("http://localhost")) {
requiresAccountAspect.checkAccount(joinPoint);
}
return joinPoint.proceed();
}
}
因此,在您使用 RequiresAccount
注释的任何地方,您都可以改用此包装器。例如:
@GetMapping("/test")
@RequiresAccountWrapper
public String h() {
return "test";
}
如您所见,我正在创建方面的新实例。我不知道您是否有权访问 Aspect-class 本身,但如果您有,则可以调用其中的方法并传递 joinPoint。要从请求中找到 URL,您可以注入 HttpServletRequest
.
假设我在另一个库中引入了一个注解 (@RequiresAccount),我在我的项目中使用了它,有没有办法有条件地将它应用到一个方法中,例如当客户来自A网站时应用它,当客户来自B网站时不应用?
我已经看了一下,我发现的唯一可能是创建包装器注释:
@Aspect
@Component
public class RequiresAccountWrapperAspect {
@Autowired
private HttpServletRequest request;
private RequiresAccountAspect requiresAccountAspect = new RequiresAccountAspect();
@Around("@annotation(com.example.demo.components.RequiresAccountWrapper)")
public Object checkIfRequiresAccount(ProceedingJoinPoint joinPoint) throws Throwable {
String requestURL = request.getRequestURL().toString();
if (requestURL.startsWith("http://localhost")) {
requiresAccountAspect.checkAccount(joinPoint);
}
return joinPoint.proceed();
}
}
因此,在您使用 RequiresAccount
注释的任何地方,您都可以改用此包装器。例如:
@GetMapping("/test")
@RequiresAccountWrapper
public String h() {
return "test";
}
如您所见,我正在创建方面的新实例。我不知道您是否有权访问 Aspect-class 本身,但如果您有,则可以调用其中的方法并传递 joinPoint。要从请求中找到 URL,您可以注入 HttpServletRequest
.