java - ServletRegistrationBean 是否为每个注册的子 WebApplicationContext 使用不同的类加载器

标签 java spring spring-boot classloader

我遇到过这样的情况:我使用 ServletRegistrationBean 向 Spring 父 Web 应用程序上下文注册两个子 Web 应用程序上下文,并为每个子 Web 应用程序上下文提供不同的 DispatcherServlet 实例。它们每个都在不同的上下文路径下提供服务。

这里的主要问题是每个 ServletRegistrationBean 都有一个使用相同第三方库的 bean,它使用 static 中的 getInstance() > 成员(member)。预期的行为是每个 ServletRegistrationBean 都有该类的一个实例。因此,当从第二个 ServletRegistrationBean 调用 getInstance() 时,将提供新实例,而不是在第一个 ServletRegistrationBean 中创建的实例。

问题是,两个不同的 ServletRegistrationBean 中的 bean 是否会被创建,并且在内部会使用不同的类加载器实例?

最佳答案

根据 Spring 文档:

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.

所以,我相信,将会创建两个不同的ServletRegistrationBean。如果你需要一个真正的单例,你需要用老式的方式来做——私有(private)构造函数,静态 getInstance 方法和代码来处理序列化(如果你实现了可序列化)。 更多这里: http://docs.spring.io/spring/docs/3.0.0.M3/spring-framework-reference/html/ch04s04.html#beans-factory-scopes-singleton

关于java - ServletRegistrationBean 是否为每个注册的子 WebApplicationContext 使用不同的类加载器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34161242/

相关文章:

java - 如何比较 Type 的实例是否相等

java - 如何生成空bpm :comment box in Alfresco Activiti Workflow Task?

java - Spring 支持 MIME 类型 "multipart/byteranges"

spring-boot - 如何使用 Spring Boot 嵌入式 tomcat 设置 Tomcat session 复制

java - @EnableJpaRepositories 未检测到或在 spring-boot 应用程序的任何地方都未检测到存储库的 @Autowired

java - 为什么此标记生成器返回不正确的值?

java - Spring 3.x 和 Hibernate Envers

spring - @Async 会发生什么。是否超时?

java - 在 Spring Hibernate 中操作 JSON 数组

javascript - 如何将 javascript (js) Map 传递给 spring boot Controller?