Spring MVC @Scope proxy bean & Jackson 2

I am trying to develop a small Spring MVC application where I would like the User object to be initialized from the beginning of each session.

I have a 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 the MyUser object once Spring Security recognizes the user in the Interceptor class (Btw, is this 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 the Controller processes the request, there is already an initialized User Session class. But when I try to serialize the MyUser object with Jackson, it just doesn'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 objects work well with the Controller class, but Jackson does not.

When I remove the @Scope annotation from the User object, Jackson serialization will start working.

Obviously the area with the bean proxy and singleton Controller is a problem

But how can I fix this?

-

, , :) , ? MyUser ? ?

+4
1

, , - :

@Component
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class MyScopedUser implements User {

    private MyUser myUser;
    // private fields
    // getters and setters


    public void fillByName(String username) {
        userDao.select(username);
    }

    public MyUser getMyUser() {
        return this.myUser;
    }
}

, MyScopedUser -, . :

mapper.writeValueAsString(scopeUser.getMyUser())
+2

All Articles