gpt4 book ai didi

java - 如何包装注释并有条件地将其应用于方法

转载 作者:太空宇宙 更新时间:2023-11-04 09:24:35 25 4
gpt4 key购买 nike

假设我在另一个库中引入了一个注释(@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 类本身,但如果有的话,您可以调用其中的方法并传递 joinPoint。要从请求中查找 URL,您可以注入(inject) HttpServletRequest

关于java - 如何包装注释并有条件地将其应用于方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57878876/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com