创建注释以执行常见操作并返回结果

时间:2017-05-18 07:27:21

标签: java spring annotations

我有一个带有两个端点的Spring REST控制器,它们通过包含请求处理程序的相应FooBar返回FooManager.handleFooBarManager.handleBar

/MyService/foo

/MyService/bar

为了能够检索到正确的FooBar,我需要为主叫用户访问GroupId。传入的请求将包含UserId。然后可以使用UserId对另一个服务/OtherService/baz/{UserId}进行后端REST调用,OtherService将为给定的GroupId返回UserId

现在我想"隐藏"提取GroupId因为我需要为我从服务返回的所有资源提取它。我想要一个小注释来触发获取GroupId并且还返回结果的代码。类似的东西:

class FooManager {

  @RequireGroupId
  public Foo handleFoo(GroupId groupId) { ... }

}

到目前为止,我已经查看了Annotation Processing 101Spring custom annotationsCustom validation annotation in Spring,但如果这些文章有任何不同,那么这些文章似乎都没有返回值,也没有进行网络调用。< / p>

所以:

  1. 如果可能,我如何实现这样的注释和处理器?
  2. 如果没有,我如何才能有效地使OtherService的请求尽可能透明?

1 个答案:

答案 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
    }

}