I'm trying to develop a small Spring MVC application, where i'd like User object to initialize from the beginning of each session.
I have the User class
@Component
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class MyUser implements User {
// private fields
// getters and setters
public void fillByName(String username) {
userDao.select(username);
}
}
And i want to initialize MyUser object once Spring Security recognize the user, in Interceptor Class (Btw, is it a good practice?)
public class AppInterceptor extends HandlerInterceptorAdapter {
@Autowired
MyUser user;
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (!(auth instanceof AnonymousAuthenticationToken)) {
user.fillByName(auth.getName());
}
return true;
}
}
So, when Controller handles the request, there is already initialized session scoped User class. But when i try to serialize MyUser object with Jackson, it just doesnt't work:
@RequestMapping("/")
public String launchApp(ModelMap model) {
ObjectMapper mapper = new ObjectMapper();
try {
System.out.println(user.getUsername()); // Works good!
model.addAttribute("user", mapper.writeValueAsString(user)); // Doesn't work
} catch (JsonProcessingException e) {
// @todo log an error
}
return "app/base";
}
As you can see, MyUser object getters work good from the Controller class, but Jackson - doesn't.
When i remove @Scope annotation from User object, Jackson serialization start working.
Obviously, scoped proxy bean and singleton Controller class are the problem
But how i can fix it?
--
UPDATE
Looks like i'm first who came across this :) Maybe it is bad architecture? Should i create a new instance of MyUser class in the Controller? What is the common practice?