Java 带有 EJB 配置的 JNDI

Java JNDI with EJB configuration

我对 EJB 3.1 和 Oracle 12.1 DB 的 JNDI 配置有疑问。 我的代码:

    private static NewSessionBeanRemote lookupRemoteSessionBean() throws NamingException {

    final Hashtable jndiProperties = new Hashtable();
    jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");

    final Context context = new InitialContext(jndiProperties);
    final String appName = "";
    final String moduleName = "EjbComponent";
    final String distinctName = "";
    final String beanName = NewSessionBean.class.getSimpleName();
    final String viewClassName = NewSessionBeanRemote.class.getName();
    System.out.println("ejb:" + appName + "" + moduleName + "" + distinctName + "/" + beanName + "!" + viewClassName);
    return (NewSessionBeanRemote) context.lookup("ejb:" + appName + "" + moduleName + "" + distinctName + "/" + beanName + "!" + viewClassName);
}

当我尝试查找 jndi 时出错:

javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:662)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:313)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:350)
at javax.naming.InitialContext.lookup(InitialContext.java:417)
at com.studio.java.client.EjbTester.lookupRemoteSessionBean(EjbTester.java:73)
at com.studio.java.client.EjbTester.invokeStatelessBean(EjbTester.java:51)
at com.studio.java.client.EjbTester.main(EjbTester.java:41)

除了您的 Context.URL_PKG_PREFIXES 您还需要设置以下属性:

jndiProperties.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
jndiProperties.put(Context.PROVIDER_URL, "http-remoting://127.0.0.1:8080");

此外,如果您有任何类型的身份验证,则必须通过 Context.SECURITY_PRINCIPALContext.SECURITY_CREDENTIALS:

进行设置
jndiProperties.put(Context.SECURITY_PRINCIPAL, "username");
jndiProperties.put(Context.SECURITY_CREDENTIALS, "password");