There are many different ways but it depends on your needs:
To load a property file from $TOMCAT_HOME/conf
directory you will need to access it using a java.io.File
object since the class loader (as in this.getClass().getClassLoader().getResourceAsStream(...)
is just able to load files (and classes) from your class path (under WEB-INF/classes
, WEB-INF/lib
or $TOMCAT_HOME/lib
).
The easiest example to load a file from the Tomcat's config directory would be:
File configDir = new File(System.getProperty("catalina.base"), "conf");
File configFile = new File(configDir, "myconfig.properties");
InputStream stream = new FileInputStream(configFile);
Properties props = new Properties();
props.load(stream);
Notice that this approach will make your code dependent of Tomcat (the loading mechanism depends on the fact of a Tomcat's system property being available). This is something that I wouldn't recommend at all so if you move your property file to a folder inside your classpath then you should be able to load it the way you tried and your application could be deployed in any container.
And, you could configure your properties as JNDI resources but it would be too much hassle to access them.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…