Spring session-scoped beans (controllers) and references to services, in terms of serialization

前端 未结 6 1138
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-27 12:44
  • a standard case - you have a controller (@Controller) with @Scope(\"session\").
  • classes put in the session usually are expected to i
6条回答
  •  醉梦人生
    2020-11-27 13:05

    It appears that bounty didn't attract a single answer, so I'll document my limited understanding:

    @Configuration
    public class SpringConfig {
    
        @Bean 
        @Scope(proxyMode = ScopedProxyMode.TARGET_CLASS) 
        MyService myService() {
            return new MyService();
        }
    
        @Bean
        @Scope("request")
        public IndexBean indexBean() {
            return new IndexBean();
        }
    
        @Bean
        @Scope("request")
        public DetailBean detailBean() {
            return new DetailBean();
        }
    }
    
    public class IndexBean implements Serializable {
    
        @Inject MyService myService;
    
        public void doSomething() {
            myService.sayHello();
        }
    }
    
    public class MyService {
        public void sayHello() {
            System.out.println("Hello World!");
        }
    }
    

    Spring will then not inject the naked MyService into IndexBean, but a serializable proxy to it. (I tested that, and it worked).

    However, the spring documentation writes:

    You do not need to use the in conjunction with beans that are scoped as singletons or prototypes. If you try to create a scoped proxy for a singleton bean, the BeanCreationException is raised.

    At least when using java based configuration, the bean and its proxy can be instantiated just fine, i.e. no Exception is thrown. However, it looks like using scoped proxies to achieve serializability is not the intended use of such proxies. As such I fear Spring might fix that "bug" and prevent the creation of scoped proxies through Java based configuration, too.

    Also, there is a limitation: The class name of the proxy is different after restart of the web application (because the class name of the proxy is based on the hashcode of the advice used to construct it, which in turn depends on the hashCode of an interceptor's class object. Class.hashCode does not override Object.hashCode, which is not stable across restarts). Therefore the serialized sessions can not be used by other VMs or across restarts.

提交回复
热议问题