Adding session synchronization to Spring MVC

2019-04-14 22:57发布

问题:

I need to add session synchronization to a Spring MVC application. I'm using Spring 3.1.2.

The synchronization is required because I will have multiple AJAX calls updating session data. Rather than synchronize the session data within the web app, the design decision was made to force the incoming calls to be processed synchronously.

In my servlet.xml, I have the following:

<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="synchronizeOnSession" value="true" />
</bean>

Yet if I do two AJAX calls from the same session to the same request handler, they both will execute at the same time. I was expecting the synchronizeOnSession to prevent this.

Am I missing something in the configuration?

回答1:

I ended up adding a BeanPostProcessor to set the synchronizeOnSession flag.

Added this new class:

@Component
public class MyPostProcessor implements BeanPostProcessor
{
  @Override
  public Object postProcessBeforeInitialization( Object bean, String name ) throws BeansException
  {
    if( bean instanceof RequestMappingHandlerAdapter )
    {
      RequestMappingHandlerAdapter adapter = ( RequestMappingHandlerAdapter ) bean;
      adapter.setSynchronizeOnSession( true );
    }

    return bean;
  }

  @Override
  public Object postProcessAfterInitialization( Object bean, String beanName ) throws BeansException
  {
    return bean;
  }
}

Along with a component scan entry in the application context:

<context:component-scan base-package="com.company.base.spring.MyPostProcessor" />

You can set a breakpoint in the RequestMappingHandlerAdapter (org.springframework.web.servlet.mvc.method.annotation) at handleInternal(...) to confirm that the synchronizeOnSession is set to true.