Tomcat 中的类加载器之谜+春季环境
我有两个用于 A 类的 java 静态方法:
private static String value;
public static void setValue(String str) {
value = str;
}
public static String getValue() {
return value;
}
听起来很简单。我调用 A.setValue("someValue"),然后在 spring 应用程序上下文加载的其他一些类中,我调用 A.getValue(),我得到 null 返回;同时,在原来的地方,A.getValue()仍然返回“someValue”。
所以在我看来,tomcat JVM 中有同一个 java 类的两个实例。有没有一种方法可以确保一个java类只有一个实例?
谢谢。
I have two java static methods for class A:
private static String value;
public static void setValue(String str) {
value = str;
}
public static String getValue() {
return value;
}
sounds simple. I call A.setValue("someValue"), then in some other classes which loaded by spring application context, I call A.getValue(), I am getting null back; while at the same time, in the original place, the A.getValue() still returns "someValue".
So it seems to me there are two instances of the same java class in the tomcat JVM. Is there some way to make sure there is only one instance for one java class?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
也许您实际上这里没有单例,并且看到类 A 由两个不同的类加载器加载?在这种情况下,一种解决方案是创建 Spring bean(不是作为原型)并将其注入到您正在使用它的两个位置 - 这样框架就可以管理单例的生命周期。如果这仍然是一个问题,您可能需要考虑上述设计,特别是关于并发访问的设计。
Perhaps you actually don't have a singleton here and are seeing the class A loaded by two different class loaders? One solution in this case would be to have the Spring bean created (not as prototype) and injected into the two places you are using it - so the framework manages the life cycle of the singleton. If this is still a problem you might want to consider the design of the above, specifically with regards to concurrent access.