---
title: " resource-ref和resource-env-ref的区别"
author: "tisty"
date: "2008-11-29T13:12:09Z"
tags: ["JDBC", "JMS", "SQL", "Web", "配置管理"]
slug: "resource-ref-resource-env-ref"
draft: false
lastmod: "2008-11-29T13:12:40Z"
id: 282849
url: "https://tisty.iteye.com/blog/282849"
---

可以在/WEB-INF/web.xml中定义资源的特性。使用JNDI查找&lt;resource-ref&gt; 和&lt;resource-env-ref&gt;元素时，这些特性被返回。对同一资源名称，还必须定义资源参数，这些参数用来配置对象工厂（object factory）以及对象工厂的属性。  
例如，web.xml:

![](http://www.cnjsp.org/document/images/void.gif) ![](http://www.cnjsp.org/document/images/void.gif) ![](http://www.cnjsp.org/document/images/void.gif) ![](http://www.cnjsp.org/document/images/void.gif)

```
<resource-ref>
  <description>Employees Database for HR Applications</description>
  <res-ref-name>jdbc/EmployeeDB</res-ref-name>
  <res-ref-type>javax.sql.DataSource</res-ref-type>
  <res-auth>Container</res-auth>
</resource-ref>
<resource-env-ref>
  <resource-env-ref-name>jms/StockQueue</resource-env-ref-name>
  <resource-env-type>javax.jms.Queue</resource-env-ref-type>
</resource-env-ref>
```

![](http://www.cnjsp.org/document/images/void.gif) ![](http://www.cnjsp.org/document/images/void.gif) ![](http://www.cnjsp.org/document/images/void.gif) ![](http://www.cnjsp.org/document/images/void.gif)

 

&lt;resource-ref&gt;/&lt;resource-env-ref&gt;元素的有效属性如下：

属性描述 `res-auth`

指定是web应用代码本身sign on到对应的resource mananger，还是由container代表web应用sign on到resource manager。该属性的值必须是Application或者Container。如果在web application deployment descriptor中使用&lt;resource-ref&gt;，这个属性是必需的，如果使用&lt;resource-env-ref&gt;，这个属性是可选的。

`description`

资源的文字描述（可选）

**`res-ref-name/ res-env-ref-name`**

资源的名称，相对于java:comp/env context

`res-sharing-scope`

指定通过这个resource manager得到的连接是否共享。该属性的值必须是Shareable或者Unshareable。缺省情况下，假定连接是共享的。

**`res-ref-type/ res-env-ref-type`**

当web应用查找该资源的时候，返回的Java类名的全称。

两者对比：  
&lt;resource-ref&gt;--资源引用，一般声明管理资源，如数据库驱动程序、JavaMail Session、自定义类工厂等。  
&lt;resource-env-ref&gt;--资源环境引用，在Servlet 2.4里用来简化设置不需认证信息的资源环境,一般声明与资源相关的被管理对象，如环境参数、resource-ref变量。