【问题标题】:How to avoid the need to pass the same parameter to all methods?如何避免需要将相同的参数传递给所有方法?
【发布时间】:2015-04-05 10:06:00
【问题描述】:

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

我的问题是,其中许多方法调用需要用户和应用程序请求它的外部 API。

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

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

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

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

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

【问题讨论】:

    标签: java spring stateless


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 我的解决方案是将 RequestInformation 会话设置为范围,并使用范围代理将其注入到单例服务类中。
    猜你喜欢
    • 2020-04-15
    • 2018-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多