我有一个带有两个端点的Spring REST控制器,它们通过包含请求处理程序的相应Foo
和Bar
返回FooManager.handleFoo
和BarManager.handleBar
:
/MyService/foo
/MyService/bar
为了能够检索到正确的Foo
和Bar
,我需要为主叫用户访问GroupId
。传入的请求将包含UserId
。然后可以使用UserId
对另一个服务/OtherService/baz/{UserId}
进行后端REST调用,OtherService
将为给定的GroupId
返回UserId
。
现在我想"隐藏"提取GroupId
因为我需要为我从服务返回的所有资源提取它。我想要一个小注释来触发获取GroupId
并且还返回结果的代码。类似的东西:
class FooManager {
@RequireGroupId
public Foo handleFoo(GroupId groupId) { ... }
}
到目前为止,我已经查看了Annotation Processing 101,Spring custom annotations和Custom validation annotation in Spring,但如果这些文章有任何不同,那么这些文章似乎都没有返回值,也没有进行网络调用。< / p>
所以:
OtherService
的请求尽可能透明?答案 0 :(得分:1)
注释只是用它做一些事情的标记。逻辑应该检查方法是否有注释并在这种情况下应用一些代码
我建议使用Aspects
检查 https://www.mkyong.com/spring3/spring-aop-aspectj-annotation-example/和http://www.journaldev.com/2583/spring-aop-example-tutorial-aspect-advice-pointcut-joinpoint-annotations
@Aspect
public class GroupIdRetrieverAspect {
@Before("execution(* com.your.package.*)")
public void logBefore(JoinPoint joinPoint) {
System.out.println("logBefore() is running!");
//use joinPoint to get called class/method
//check whether called method has your annotation and retrieve the id
}
}