简体   繁体   中英

Session scoped bean works in out of session threads

I have a bean defined with scope="session" and created via <aop:scoped-proxy/> , however, when I access such scoped CGLIB proxy, it works even outside the session, which is wrong. I have tried both autowiring that proxy in or getting it directly from application context, however, each time even in completely new thread that was never part of session of any request, I get actual value from the proxy instead of proxy being null or proxy throwing exception.

Here is example bean definition

<bean id="commons" class="foo.bar.Commons" scope="session">
    <aop:scoped-proxy/>
    <property name="securityEnabled" value="true"/>
    <property name="modificationAllowed" value="true"/>
    <property name="autoSave" value="true"/>
</bean>

And here is how I use it:

public class CommonsModificatorProvider implements ModificatorProvider, ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public String getCurrentModificator() {
        try {
            Commons commons = applicationContext.getBean(Commons.class);
            if (commons == null)
                return "system";
            String user = commons.getCurrentUser();
            if (user == null)
                return "system";
            return user;
        } catch (Exception e) {
            return "system";
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}

however, even in completely new thread, getCurrentUser() always returns some value.

I have tried making CommonsModificationProvider prototype scoped and instead of autowiring it, I instantiated it every time from application context where appropriate, but no difference. It will get same CGLIB proxy as autowired 'singleton' scoped version.

Okay, apparently spring is trying to be helpful and saves the session if you start thread inside a session (who though that is remotely okay is beyond me).

To fix, you have to call RequestContextHolder.resetRequestAttributes(); inside your new thread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM