您的位置:首页 > 运维架构 > Tomcat

Tomcat5 中JNDI Resources配置 ------ 通用JavaBean资源配置(Generic JavaBean Resources)

2006-05-27 22:36 399 查看
Tomcat5 中JNDI Resources配置 ------ 通用JavaBean资源配置(Generic JavaBean Resources)

通常有四个步骤:
1.首先,当然是建一个JavaBean了。

package com.mycompany;

public class MyBean {

private String foo = "Default Foo";

public String getFoo() {
return (this.foo);
}

public void setFoo(String foo) {
this.foo = foo;
}

private int bar = 0;

public int getBar() {
return (this.bar);
}

public void setBar(int bar) {
this.bar = bar;
}

}

2.在web.xml文件中添加如下信息:

<resource-env-ref>
<description>
Object factory for MyBean instances.
</description>
<resource-env-ref-name>
bean/MyBeanFactory
</resource-env-ref-name>
<resource-env-ref-type>
com.mycompany.MyBean
</resource-env-ref-type>
</resource-env-ref>

3.配置Tomcat的资源工厂:
<Context ...>
...
<Resource name="bean/MyBeanFactory" auth="Container"
type="com.mycompany.MyBean"/>
<ResourceParams name="bean/MyBeanFactory">
<parameter>
<name>factory</name>
<value>org.apache.naming.factory.BeanFactory</value>
</parameter>
<parameter>
<name>bar</name>
<value>23</value>
</parameter>
</ResourceParams>
...
</Context>

这段代码可以添加到server.xml中的<host>标签之间,不过,我觉得还是加到每个Tomcat应用所对应的 .xml文件中比较好,易于理解,也不容易出错。

4.上述步骤完成之后,就可以在代码中使用配置好的资源了。使用方法示例如下:

Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
MyBean bean = (MyBean) envCtx.lookup("bean/MyBeanFactory");

writer.println("foo = " + bean.getFoo() + ", bar = " +
bean.getBar());

有些需要特别注意的地方如下:
1.)web.xml中添加的元素的顺序不能改变。
2.)在server.xml中添加<context>元素,和在某个web应用对应的 .xml文件中添加<context>元素都可以访问配置好的资源。Tomcat会先检查server.xml,如果两个有相同的配置的话,Tomcat会以server.xml中的为准,并且删除该应用对应的.xml文件,然后产生一个新的。这个新的只包含一个<context>根元素,不包含<resource>元素及其中的其他元素。
3.)资源名称(例子中的是bean/MyBeanFactory,即<Resource>元素中的name属性的值)必须和web.xml中指定的<resource-env-ref-name>的值相同。另外,在资源工厂的参数配置中可以指定JavaBean的属性的初始值。示例代码中就把Bar属性的值设为23了。(JavaBean中Bar的默认值是0).不指定的话,就使用程序中设置的初始值.
原文:
Note that the resource name (here, bean/MyBeanFactory must match the value specified in the web application deployment descriptor. We are also initializing the value of the bar property, which will cause setBar(23) to be called before the new bean is returned. Because we are not initializing the foo property (although we could have), the bean will contain whatever default value is set up by its constructor.

原文网址: http://tomcat.apache.org/tomcat-5.0-doc/jndi-resources-howto.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: