开发者

A jar in tomcat's lib can't see a properties file in my webapp

Recently I separated the core functionality of my core servlets application into a jar file. This jar file is now deployed in tomcat's lib folder and the application(i.e. servlets, jsps, properties files..etc) is deployed independently as a war file.

The jar files needs specific properties files. I place these properties files right under the "src" folder(i.e. in the top of the classes hierarchy) in the war file.

In the past when everything was in the same project and deployed in one war file. The properties files were accessible by the related classes. Now when these classes are deployed in a jar, they can't see the properties files located in the war file (i.e. deployed web application).

What could I be missing here ? An example how I load my proeprties files:

properties.load(getClass().getResou开发者_如何学编程rceAsStream("/appconfig.properties"));

Thank you for your time.


You shouldn't get it by the class' own classloader. As the class is now managed by Tomcat, it only knows about Tomcat's internal resources, not about webapp-specific resources. You should get it by the context classloader of the current thread. That classloader knows about all resources dedicated to the current webapp.

properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("appconfig.properties"));

Regardless of this, the proper location of such a properties file representing the global app configuration would not be inside the WAR file. You should rather place the properties file on a fixed path outside Tomcat and the WAR file and then add that fixed path to the shared.loader property of Tomcat's /conf/catalina.properties so that it becomes part of the classpath. This allows you for freely editing the configuration file without the need to rebuild/redeploy the whole WAR. Note that you still need to use the context classloader to load it.


Yes, that won't work because the jars in tomcat lib folder are loaded by a different classloader that knows nothing about your webapp's classes. In other words, tomcat lib is the parent class loader of the webapp classloader (which are created one per each webapp).

If you want to make it work, you can either place the properties file in an external location and make it known to the jar inside tomcat lib via absolute file path or place the jar back inside webapp's lib.

Here's some reference from the Tomcat site.

http://tomcat.apache.org/tomcat-7.0-doc/class-loader-howto.html

Typically, environment variables are used to identify $CATALINA_HOME which will then be prefixed to the relative file path in order to avoid hardcoding the absolute paths.

String catalinaHome = System.getProperty("CATALINA_HOME");
properties.load(new FileInputStream(new File(catalinaHome + "/path/to/appconfig.properties")));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜