如何在WebSphere中读取外部属性文件?

use*_*071 3 java websphere

我开发了一个示例Web应用程序,它将从外部属性文件中读取数据.属性文件位于系统的源文件夹中,不包含在WAR文件中.

属性文件的访问方式如下:

Properties prop = new Properties();
//File f1 = new File("Property.properties");
prop.load(getClass().getClassLoader().getResourceAsStream("Property.properties"));
Run Code Online (Sandbox Code Playgroud)
  1. 如何在WAR文件外部访问此属性文件?
  2. 在WAR文件中读取代码需要进行哪些更改?

Jac*_*ski 7

我认为最通用的方法是在一节所述定义一个简单的环境条目EE.5.4简单的环境条目Java™平台,企业版(Java EE)规范,V5.

从部分(第68页):

简单环境条目是用于自定义应用程序组件的业务逻辑的配置参数.环境条目值可以是以下Java类型之一:String,Character,Byte,Short,Integer,Long,Boolean,Double和Float.

您还可以使用URL连接工厂,如规范EE.5.6.1.4标准资源管理器连接工厂类型部分所述.

Application Component Provider必须使用java.net.URL资源管理器连接工厂类型来获取URL连接.

两者都需要在WEB-INF/web.xmlWeb应用程序的部署描述符中定义资源引用,以便您可以@Resource使用JNDI API java:comp/env作为入口点来注入值.

好处是,你可以改变你的web应用程序的配置,而无需重新编译代码,以及让你使用你的管理员习惯于与应用程序服务器的管理工具进行更改.

web.xml您定义资源引用.

<resource-ref>
  <res-ref-name>propertiesURL</res-ref-name>
  <res-type>java.net.URL</res-type>
  <res-auth>Container</res-auth>
  <res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
<resource-ref>
  <res-ref-name>propertiesPath</res-ref-name>
  <res-type>java.lang.String</res-type>
  <res-auth>Container</res-auth>
  <res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
Run Code Online (Sandbox Code Playgroud)

然后在您的代码中使用以下内容来访问值:

@Resource
String propertiesPath;

@Resource
URL propertiesURL;
Run Code Online (Sandbox Code Playgroud)

通过这种方式,您满足了Java EE的要求,您可以使用propertiesPathpropertiesURL好像它们作为输入参数传递给您的方法.

现在,是时候满足WebSphere Application Server的期望了.

您定义的是需要映射到其管理名称的逻辑名称(应用程序服务器知道并可以提供给应用程序).

在WebSphere Application Server中,您将WebSphere Binding描述符WEB-INF/ibm-web-bnd.xml与以下配置一起使用:

<?xml version="1.0" encoding="UTF-8"?>
<web-bnd xmlns="http://websphere.ibm.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://websphere.ibm.com/xml/ns/javaee http://websphere.ibm.com/xml/ns/javaee/ibm-web-bnd_1_1.xsd"
  version="1.1">

  <virtual-host name="default_host" />

  <resource-ref name="propertyURL" binding-name="propertyURL" />
  <resource-ref name="propertyURL" binding-name="propertyURL" />
</web-bnd>
Run Code Online (Sandbox Code Playgroud)

部署应用程序时,WAS允许您将这些映射映射到其管理的资源.使用ISC控制台定义环境条目的值并将它们映射到应用程序.

使用WebSphere Liberty Profile变得更容易.我在我的文章中使用@Resource来访问WebSphere AS 8.5 Liberty Profile中的JNDI,描述了WLP提供的机制.