I currently have a REST Web service using Spring's RestController. I implemented a HandlerInterceptorAdapter where I want to set some user data.
Code is like this:
@Component
public class UserContextInterceptor extends HandlerInterceptorAdapter {
@Autowired
private UserContext userContext;
@Override
public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//set userContext here
userContext.setLoginId("loginId");
return true;
}
}
Here is the RestController:
@RestController
public class MyController {
@Autowired
private MyService myService;
@GetMapping
public Response processRequest(Request request) {
return myService.processRequest(request);
}
}
Here is the Service. This is just called by the controller:
@Service
public class MyService {
@Autowired
private UserContext userContext;
public Response processRequest(Request request) {
//process request using userContext
if (userContext.getLoginId() == null)
throw new InvalidloginException("No login id!");
//do something else
return new Response();
}
}
The UserContext is just a POJO containing user-specific fields.
In my implementation, the UserContext I think is not thread safe. The UserContext object would be overridden everytime a request comes. I would like to know how to properly autowire/annotate it in such a way that I want a new UserContext everytime a request comes in. And that UserContext would be properly injected in MyService. This means that all calls in MyService.processRequest would always have a different UserContext injected to it.
One solution I was thinking of was just to pass the UserContext object in the MyService.processRequest() method. I was just wondering if this can be solved using Spring's autowire or other annotations.
Any ideas?
Thanks!