如何在JBOSS中设置JNDI变量?

Tri*_*Man 2 jboss java-ee

我正在使用JBoss 5.1,我想将配置文件的位置指定为JNDI条目,以便我可以在我的Web应用程序中查找它.我怎样才能正确地做到这一点?

Nic*_*las 6

有两种主要方法可以做到这一点.

部署描述符/声明

通过在诸如*my-jndi-bindings*** - service.xml**之类的文件中创建部署描述符来使用JNDI绑定管理器,并将其放入服务器的deploy目录中.示例描述符如下所示:

<mbean code="org.jboss.naming.JNDIBindingServiceMgr" 
       name="jboss.tests:name=example1">
    <attribute name="BindingsConfig" serialDataType="jbxb">
        <jndi:bindings xmlns:xs="http://www.w3.org/2001/XMLSchema-instance" 
                       xmlns:jndi="urn:jboss:jndi-binding-service"
                       xs:schemaLocation="urn:jboss:jndi-binding-service  \
               resource:jndi-binding-service_1_0.xsd"> 
            <jndi:binding name="bindexample/message">
                <jndi:value trim="true">
                    Hello, JNDI!
                </jndi:value>
            </jndi:binding>
        </jndi:bindings>
    </attribute>
</mbean>
Run Code Online (Sandbox Code Playgroud)

程序化

获取JNDI上下文并自行执行绑定.这是执行此操作的"in-jboss"调用的示例:

import javax.naming.*;

    public static  void bind(String name, Object obj) throws NamingException {
        Context ctx = null;
        try {
            ctx = new InitialContext();
            ctx.bind(name, obj);
        } finally {
            try { ctx.close(); } catch (Exception e) {}
        }
    }
Run Code Online (Sandbox Code Playgroud)

如果名称已绑定,则可以调用rebind:

public static  void rebind(String name, Object obj) throws NamingException {
    Context ctx = null;
    try {
        ctx = new InitialContext();
        ctx.rebind(name, obj);
    } finally {
        try { ctx.close(); } catch (Exception e) {}
    }
}
Run Code Online (Sandbox Code Playgroud)

要删除绑定,请调用unbind:

public static  void unbind(String name) throws NamingException {
    Context ctx = null;
    try {
        ctx = new InitialContext();
        ctx.unbind(name);
    } finally {
        try { ctx.close(); } catch (Exception e) {}
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您尝试远程执行此操作(即不在JBoss VM中),则需要获取远程JNDI上下文:

import javax.naming.*;
String JBOSS_JNDI_FACTORY = "org.jnp.interfaces.NamingContextFactory";
String JBOSS_DEFAULT_JNDI_HOST = "localhost";
int JBOSS_DEFAULT_JNDI_PORT = 1099;
.....
Properties p = new Properties();
p.setProperty(Context.INITIAL_CONTEXT_FACTORY, JBOSS_JNDI_FACTORY);
p.setProperty(Context.PROVIDER_URL, JBOSS_DEFAULT_JNDI_HOST + ":" + JBOSS_DEFAULT_JNDI_PORT);
Context ctx = new InitialContext(p);
Run Code Online (Sandbox Code Playgroud)