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

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值