在多用户管理中想把每个用户的信息都保存在session中,其中保存用户信息的bean想用spring管理,则必须不是单例
@Controller
@Scope("prototype")
public class LoginController {
@Autowired
private LoginService loginService;
@Resource
private UserContext userContext;
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login() {
return "login";
}
@RequestMapping(value = "/login", method = RequestMethod.POST)
public ModelAndView loginCheck(User user,HttpServletRequest request) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("login");
User userInfo = loginService.getUser(user);
if (null != userInfo) {
// UserContext userContext = new UserContext();
userContext.init(userInfo);
request.getSession().setAttribute("user", userContext);
if(userInfo.getId() !=1) {
modelAndView.setViewName("redirect:/matches");
}else {
modelAndView.setViewName("redirect:/home");
}
} else {
modelAndView.addObject("user",user);
modelAndView.addObject("msg", "Invalid account or password.");
}
return modelAndView;
}
-------------
@Service
@Scope("prototype")
public class UserContext {
private List<Menu> menuList = null;
private User user = null;
private ContentOwnerContext currentContentOwner;
------------、
Scope prototype means that every time you ask spring (getBean or dependency injection) for an instance it will create a new instance and give a reference to that.
注意想得到prototype的UserContextze则必须在controller也加上@Scope,否则还是单例,因为Controller还是单例。