October 22, 2024
Chicago 12, Melborne City, USA
java

Spring: How to initialize a service bean with authenticated user info


It seems to be a common case, but I can’t still find a proper solution.

I have a service that is tightly coupled with currently authenticated user. It should receive a userId from a higher context (Controller) as an argument in one way or another. The service cannot access the userId from any globally available ‘auth’ context, it has to be received as an argument.

The service also needs to be a bean (@Service), thus it should be auto-initialized by Spring.

One way to achieve that is the following:

  1. Initialize the service without userId
  2. Then pass userId to every method that is called on the service:
@Service
class MyService
  public void method1(int userId) {
    // do something with userId
  }

  public void method2(int userId) {
    // do something with userId
  }
end

// Usage
myService = new MyService(); // This is done by Spring (with no problem).
myService.method1(getUserIdFromAnyAuthContext())
myService.method2(getUserIdFromAnyAuthContext())

The way I would like my service to work (if it wasn’t a bean) is the following:

@Service
class MyService
  private int currentUserId;

  public MyService(int currentUserId) {
    this.currentUserId = currentUserId;
  }

  public void method1() {
    // do something with currentUserId
  }

  public void method2() {
    // do something with currentUserId
  }
end

// Usage
myService = new MyService(getUserIdFromAnyAuthContext()); // I want Spring to be able to do it and have MyService as a bean.
myService.method1()
myService.method2()

How to have a service as a bean and initialize it with ‘auth’ data?



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video