开发者

Spring session bean

<bean id="user" class="com.test.service.beans.User" scope="session">
    <aop:scoped-proxy/>
</bean>

<bean id="userFacade"  class="com.test.service.facade.UserFacadeImpl"  init-method="init">
    <property name="currentUser" ref="user"/>
</bean>

this is how I set contents in the current user (thinking it will be store in session)

user = userFacade.getUser(userNameorEmail);
userFacade.setCurrentUser(user);

I get the contents of the session bean like this -

User user = userFacade.getCurrent开发者_高级运维User();

The problem is I get the user as null


This is not the way it works. If you want to store someting like in a session (it is more like a Session Bean in JEE5/6), you have to store it in a field of com.test.service.beans.User. (May you should rename this class to UserSession, to make it more clear.)

Short example to make it more clear:

package com.test.service.beans;
class User[Session] {
    int userId; (getter + setter)
    ...
}

package com.test.service.facade
class UserFacadeImp {
   //set by spring
   private User[Session] user[Session];  + getter/setter

   public saveUserIdInSession(int userId) {
      this.user[Session].setUserId(userId);
   }
}

Added

Jerry asked: My question is how to design it better? I need a way to retrieve the current user object - so I make a bean named SessionObjectBean in session scope and I will have getter and setter for currentUser. 1. Would that be a good design? 2. Also, should the currentUser be in session scope too? 3. Can I store other objects like Order in the SessionObjectBean?

  • 1) I think it is a reasonable design.
  • 2) The CurrentUser must not be any Spring Manged Bean at all.
  • 3) You can "store" every normal! object in a Spring Session scoped bean.


That's not how session beans work. Session bean is not a bean stored in the session, it's (effectively) a bean whose state is stored in the session.

In other words, if you have a bean userFacade with a property currentUser, and you want value of that property to be stored in the session, you should make userFacade a session-scoped bean. Then its currentUser property (as well as other properties composing its state) will be stored in the session.

And, as far as I understand your case, User shouldn't be declared as a Spring bean at all.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜