#Recommended solution
I would create a @Bean
with @Scope
request which would hold the user and then put the appropriate entity into that holder and then take from that holder inside the method.
@Component
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class CurrentUser {
private User currentUser;
public User getCurrentUser() {
return currentUser;
}
public void setCurrentUser(User currentUser) {
this.currentUser = currentUser;
}
}
and then
@Component
public class MyInterceptor implements HandlerInterceptor {
private CurrentUser currentUser;
@Autowired
MyInterceptor(CurrentUser currentUser) {
this.currentUser = currentUser;
}
@Override
public boolean preHandle(
HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
this.currentUser.setCurrentUser(new User("whatever"));
return true;
}
}
and in the Controller
@RestController
public class HelloController {
private CurrentUser currentUser;
@Autowired
HelloController(CurrentUser currentUser) {
this.currentUser = currentUser;
}
@RequestMapping("/")
public String index() {
return currentUser.getCurrentUser().getEmail();
}
}
#Alternative solution
In case your object that you would like to have, only contains one field, you can just cheat on that and add that field to the HttpServletRequest
parameters and just see the magic happen.
@Component
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(
HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//TRY ONE AT THE TIME: email OR user
//BOTH SHOULD WORK BUT SEPARATELY OF COURSE
request.setAttribute("email", "[email protected]");
request.setAttribute("user", new User("[email protected]"));
return true;
}
}