我正在开发一个项目,它要求我使用会话令牌执行标准的HTTP调用。我正在使用自定义身份验证器构建自定义HTTP客户端,如下所示:
Client client = Client.Builder().withConfig().withAuthenticator(Authenticator);
我的身份验证器是一个界面
public interface Authenticator{
SessionToken getSessionToken(); // so that different authentication methods can be supported
}
现在,为了执行请求,我需要获取会话令牌,我通过调用authenticator.getSessionToken()
获得。但是,验证者必须调用后端来获取令牌,因为它需要客户端,从而导致循环依赖。我该如何解决这个问题?一种方法是创建一个单独的身份验证客户端,我在Authenticator Implementation的构造函数中传递,但包导入仍然显示循环依赖。有没有更好的方法来设计它?
最终,Client
并不真正需要Authenticator
;它需要一个SessionToken
。实现这一目标的一种方法是用withAuthenticator()
替换withSessionToken()
方法。显而易见的实现是直接接受SessionToken
的方法;但你也可以认为Authenticator
是一个functional interface,因此可以表示为Supplier<SessionToken>
。
无论哪种方式,如果你用Client
或Authenticator
替换SessionToken
对Supplier<SessionToken>
的依赖,你可以打破循环依赖。