简体   繁体   English

Servlet中的Singleton和Tomcat7上的其他类

[英]Singleton in Servlets and other Classes on Tomcat7

I have some Web-Apps. 我有一些Web应用程序。 Each in different v-hosts on Tomcat7. 每个位于Tomcat7上的不同虚拟主机中。 All this Web-Apps use the same collection of Librarys (written by my own), stored in WEB-INF/lib as .jar This Library has some static Classes (Logger, Config, etc). 所有这些Web应用程序都使用相同的库集合(由我自己编写),以.jar的形式存储在WEB-INF / lib中。该库具有一些静态类(记录器,配置等)。 It seams web-app X can see/use the static Instance of web-app Y. "randomly" X writes in the logging-file of Y. Y uses configs from X.... etc. 它接缝了web-app X可以看到/使用web-app Y的静态实例。“随机地” X写入Y的日志文件。Y使用X的配置。

Is this generaly a problem with the JVM(s) in Tomcat ? 这通常与Tomcat中的JVM有关吗?

Only for the Servlets i can store the static Classes in the ServletContext, but Non-Servlets cant reach them, right ? 仅对于Servlet,我可以将静态类存储在ServletContext中,但非Servlet无法访问它们,对吗?

Here the Constructor in Class Config.java 这里是Config.java类中的构造方法

public class Config{
    public static Config instance;

    private Config(){

    }
    public static Config getInstance(){
         if(instance==null) instance = new Config();
         return instance;
    }
}

In Servlet and also in other Classes i use 在Servlet和其他类中,我使用

private static Config config = Config.getInstance();

Is there any other way to share ONE instance of a Class in the whole Web-App but only in THIS web-app ? 还有其他方法可以在整个Web应用程序中共享一个Class的一个实例,但只能在此Web应用程序中共享吗?

Anything running in context /X cannot see anything in /Y/WEB-INF/lib or Y/WEB-INF/classes . 在上下文/X运行的任何内容都不会在/Y/WEB-INF/libY/WEB-INF/classes看到任何内容。 The reason is that the jars in /X/WEB-INF/lib and classes in /X/WEB-INF/classes are in a different classloader than the jars and classes for context /Y . 原因是/X/WEB-INF/lib中的jar和/X/WEB-INF/classes 中的类与上下文/Y的jar和类位于不同的类加载器中 This is not a Tomcat "problem", this is per the J2EE servlet spec. 这不是Tomcat的“问题”,这是根据J2EE Servlet规范。

I would revisit my design, but if you really need to share a class between two or more contexts, put the classes in a jar, and place the jar in ${CATALINA_HOME}/lib . 我将重新设计,但是如果您确实需要在两个或多个上下文之间共享一个类,请将这些类放在一个jar中,然后将该jar放在${CATALINA_HOME}/lib Classes in that folder are visible to all contexts, as they are loaded in a classloader that is the parent of the context classloaders. 该文件夹中的类对于所有上下文都是可见的,因为它们是作为上下文类加载器的父类加载到类加载器中的。

The "correct" way to do this is to register the object in JNDI, where every component of your app can look it up. 执行此操作的“正确”方法是在JNDI中注册对象,应用程序的每个组件都可以在其中查找对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM