java jndi tomcat_JNDI 在Tomcat中的访问方式

初始化:

Context initCtx = new InitialContext();

Context envCtx = (Context) initCtx.lookup("java:comp/env");

java:com/env为Tomcat中的初始化固定名称

0. Introduction

This resource factory can be used to create objects of any Java class that conforms to standard JavaBeans naming conventions (i.e. it has a zero-arguments constructor, and has property setters that conform to the setFoo() naming pattern. The resource factory will create a new instance of the appropriate bean class every time a lookup() for this entry is made.

The steps required to use this facility are described below.

1. Create Your JavaBean Class

Create the JavaBean class which will be instantiated each time that the resource factory is looked up. For this example, assume you create a class com.mycompany.MyBean, which looks like this:

packagecom.mycompany;publicclassMyBean {privateString foo="Default Foo";publicString getFoo() {return(this.foo);

}publicvoidsetFoo(String foo) {this.foo=foo;

}privateintbar=0;publicintgetBar() {return(this.bar);

}publicvoidsetBar(intbar) {this.bar=bar;

}

}

2. Declare Your Resource Requirements

Next, modify your web application deployment descriptor (/WEB-INF/web.xml) to declare the JNDI name under which you will request new instances of this bean. The simplest approach is to use a element, like this:

123Object factoryforMyBean instances.456bean/MyBeanFactory789com.mycompany.MyBean101112

WARNING - Be sure you respect the element ordering that is required by the DTD for web application deployment descriptors! See the Servlet Specification for details.

3. Code Your Application's Use Of This Resource

A typical use of this resource environment reference might look like this:

1Context initCtx=newInitialContext();2Context envCtx=(Context) initCtx.lookup("java:comp/env");3MyBean bean=(MyBean) envCtx.lookup("bean/MyBeanFactory");45writer.println("foo ="+bean.getFoo()+", bar ="+6bean.getBar());7

4. Configure Tomcat's Resource Factory

To configure Tomcat's resource factory, add an elements like this to the $CATALINA_HOME/conf/server.xml file, nested inside the Context element for this web application (or nested inside a DefaultContext element for the surrounding or element.

1 2 ...3 5 6 7 factory8 org.apache.naming.factory.BeanFactory9 10 11 bar12 2313 14 15 ...16 17

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值