且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 EAR 或 WAR 之外存储 Java EE 配置参数?

更新时间:2023-12-03 23:32:34

见这个 问题 用于读取 WAR 文件之外的属性文件.

See this question for reading properties file outside of the WAR file.

有关读取变量值的信息,请参阅此问题来自 JNDI.我相信这是***的解决方案.您可以使用以下代码读取字符串变量:

See this question for reading variable values from JNDI. I believe that this is the best solution. You can read a String variable with this code:

Context initialContext = new InitialContext();
String myvar = (String) initialContext.lookup("java:comp/env/myvar");

以上代码适用于所有容器.在 Tomcat 中,您在 conf/server.xml 中声明以下内容:

The above code will work on all containers. In Tomcat you declare the following in conf/server.xml:

<GlobalNamingResources ...>
  <Environment name="myvar" value="..."
         type="java.lang.String" override="false"/>
</GlobalNamingResources>

以上将创建一个全局资源.也可以在应用程序的上下文中定义资源.在大多数容器中,JNDI 资源可通过 MBean 管理控制台获得.其中一些提供了图形界面来编辑它们.进行更改时,最多需要重新启动应用程序.

The above will create a global resource. It is also possible to define a resource in the context of application. In most containers the JNDI resources are available through a MBeans Management Console. Some of them offer a graphical interface to edit them. At most an application restart is needed, when a change is made.

如何定义和编辑 JNDI 资源是特定于容器的.应用适当的设置是配置人员/管理员的工作.

How JNDI resources are defined and edited is container specific. It is the job of the configurator/administrator to apply the appropriate settings.

这些是 JNDI 提供的好处:

These are the benefits offered by JNDI:

  • 您可以在 WAR/EAR 文件中定义参数的默认值.
  • 可以在容器中轻松配置参数.
  • 修改参数值时无需重启容器.