简体   繁体   中英

Singleton in Servlets and other Classes on Tomcat7

I have some Web-Apps. Each in different v-hosts on 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). 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.

Is this generaly a problem with the JVM(s) in Tomcat ?

Only for the Servlets i can store the static Classes in the ServletContext, but Non-Servlets cant reach them, right ?

Here the Constructor in Class 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

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 ?

Anything running in context /X cannot see anything in /Y/WEB-INF/lib or Y/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 . This is not a Tomcat "problem", this is per the J2EE servlet spec.

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 . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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