从tomcat读取属性 [英] Reading properties from tomcat

查看:123
本文介绍了从tomcat读取属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为您的应用程序读取配置文件的最佳做法是什么。 tomcat服务器中的哪些文件夹是在类路径上。

What is the best practice for reading config file(s) for your application. Which folders in tomcat server are "on the classpath".

我尝试将配置文件放在 TOMCAT_HOME \ conf

I tried placing my config file in the TOMCAT_HOME\conf but still I can't read it from my servlet.

尝试使用它(在conf中有app.properties文件):

Tried using this (there is app.properties file in conf):

this.getClass().getClassLoader().getResourceAsStream("/app.properties");

我没有太多属性可能10-15我认为这不会有问题。我记得当我使用jboss时这不是问题。

I don't have much properties maybe 10-15 I figured this won't be problem. I remember when I was using jboss this wasn't issue as this much.

在我的应用程序中,我还在上下文中指定了数据库连接弹簧。 xml 我可以在那里以某种方式指定我的属性吗?或者这如何与tomcat一起使用?

In my app I also specify DB connection spring in the context.xml can I specify my properties in there as well somehow? Or how this works with tomcat?

我想保持我的财产与我的战争/解包战争分开。

I'd like to keep my properties seperate from my war/unpacked war.

更新

提出这个问题的原因是因为我不知道我的应用程序将在何处部署(在哪个位置)

Reason for asking this is because I don't know where my app will be deployed (at what location)

推荐答案

有许多不同的方法,但这取决于你的需求:

There are many different ways but it depends on your needs:

从<加载属性文件code> $ TOMCAT_HOME / conf 您需要使用 java.io.File 对象访问它的目录,因为类加载器(如在 this.getClass()。getClassLoader()。getResourceAsStream(...)只能从类路径加载文件(和类)(在<$ c $下) c> WEB-INF / classes , WEB-INF / lib $ TOMCAT_HOME / lib )。

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

从Tomcat的config目录加载文件的最简单示例是:

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);

请注意,这种方法会使您的代码依赖于Tomcat(加载机制取决于Tomcat的系统属性可用)。 这是我根本不推荐的,所以如果您将您的属性文件移动到类路径中的文件夹,那么您应该能够按照您尝试的方式加载它并且您的应用程序可以部署在任何容器中。

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.

并且,您可以将属性配置为JNDI资源,但访问它们会非常麻烦。

And, you could configure your properties as JNDI resources but it would be too much hassle to access them.

这篇关于从tomcat读取属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆