Search code examples
javaspringspring-bootclassloader

Does ServletRegistrationBean use different classloader for each registered child WebApplicationContext


I have situation where I'm registering two child web application context into Spring parent web application context, by using ServletRegistrationBean, providing different instance of DispatcherServlet to each of them. And each of them is served under different context path.

Main problem here is that each ServletRegistrationBean has one bean which is using same third-part library, which is using getInstance() from static member. And expected behavior is to have one instance of that class per ServletRegistrationBean. So when getInstance() is called from second ServletRegistrationBean, new instance will be provided, not the one created in first ServletRegistrationBean.

Question is, does beans in each of two different ServletRegistrationBean will be created and internally will use different instance of classloader?


Solution

  • According to the Spring documentation:

    Please be aware that Spring's concept of a singleton bean is quite different from the Singleton pattern as defined in the seminal Gang of Four (GoF) patterns book. The GoF Singleton hard codes the scope of an object such that one and only one instance of a particular class will ever be created per ClassLoader. The scope of the Spring singleton is best described as per container and per bean.

    So, I believe, two different ServletRegistrationBean will be created. If you need a true singleton you need to do it the old fashioned way - private constructor, a static getInstance method and code to handle serialization if you implement serializable. More here: http://docs.spring.io/spring/docs/3.0.0.M3/spring-framework-reference/html/ch04s04.html#beans-factory-scopes-singleton