Search code examples
javaspringstateless

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


In my application, I have service classes with stateless methods operating only in the method parameters.

My problem is that many of these methods call external APIs that needs the user and application requesting it.

A simple solution is to add these parameters to all service methods, something like:

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

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

I am not sure if adding the same RequestInformation parameter to all methods in all service classes is a good idea.

There is other approach I can use to avoid having the RequestInformation in all methods?


Solution

  • There is SPRING TAG in you question so assuming you are using Spring.

    You can store request specific info into session scope bean. So it will be new instance for each request:

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

    Such bean can be autowired into any spring bean.