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:
- Initialize the service without
userId
- 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