如何避免需要将相同的参数传递给所有方法?

How to avoid the need to pass the same parameter to all methods?

在我的应用程序中,我的服务 类 具有仅在方法参数中运行的无状态方法。

我的问题是这些方法中有许多会调用需要用户和应用程序请求的外部 API。

一个简单的解决方案是将这些参数添加到所有服务方法中,例如:

class RequestInformation{
    private String user;
    private String application;
}

class SomeService{
    foo(requestInformation, methodParamA, methodParamB)
    bar(requestInformation, methodParamA, methodParamB, methodParamC)
}

我不确定向所有服务中的所有方法添加相同的 RequestInformation 参数是否是个好主意类。

我可以使用其他方法来避免在所有方法中使用 RequestInformation 吗?

您的问题中有 SPRING TAG,因此假设您使用的是 Spring。

您可以将特定于请求的信息存储到会话范围 bean 中。所以它将是每个请求的新实例:

http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-factory-scopes-request

这样的 bean 可以自动装配到任何 spring bean 中。