How can I get session from a common class in Spring Boot?

五迷三道 提交于 2019-12-06 03:43:53

If I understand you right, you want to access something in the session scope from a component that a broader scope (singleton), as such the system can't know which one of the potential concurrent sessions in ther server you are interrested in an practically it would say at spring init time that the session scope isn't defined.

You can get arround that with the ObjectFactory pattern (1 of the possible solution)

@Autowired
ObjectFactory<HttpSession> httpSessionFactory;

And then when you need it, from a thread that is bound to the session:

HttpSession session = httpSessionFactory.getObject();

This way spring bind a receipe to get the object you need at the type you call the getObject() method rather than the actual object that is not yet available.

Please understand that if there no session bound to the current thread when you run the code, this will fail (return null) as no session is available. This mean either you call this code from a thread that you failed to forward the request thread local information of the request/session or you call this code from a context where it doesn't make sense.

Create session scope bean in pojo style. Inject it and use where you need set or get data from HttpSession. Spring will automatically set corresponding data into HttpSession. Eg:

@Component
@Scope(proxyMode= ScopedProxyMode.TARGET_CLASS, value=WebApplicationContext.SCOPE_SESSION)
public class SessionData {
    private Currency currency;

    public Currency getCurrency() {
        return currency;
    }

    public void setCurrency(Currency currency) {
        this.currency = currency;
    }
}


@Service
public class UserService {

   @Autowired
   private SessionData sessionData;

   public Currency getCurrentCurrency() {
       return sessionData.getCurrency();
   }

   public void setCurrentCurrency(Currency currency) {
       sessionData.setCurrency(currency);
   }
}

In such way getting/setting current currency using UserService will reflect in current HttpSession with corresponding attribute name of session bean property ('currency').

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!