创建自定义 JNDI 资源

Creating a custom JNDI resource

我想为我正在通过 context/JNDI 开发的网络应用程序提供配置。我目前正在使用捆绑的 Glassfish 服务器在 Netbeans 8.1 中进行开发,尽管我的解决方案应该与容器无关。

我有获取数据库连接的工作设置,但对自定义资源类型感到困惑。

在web.xml中:

<resource-ref>
    <res-ref-name>SHOWmail/search</res-ref-name>
    <res-type>com.example.SearchProvider</res-type>
    <res-auth>Container</res-auth>
</resource-ref>

在 glassfish-resources.xml:

    <custom-resource jndi-name="SHOWmail/search" res-type="com.example.SearchProvider" factory-class="com.example.SearchProviderFactory">
    <property name="name" value="value"/>
</custom-resource>

在代码中:

   initContext = new InitialContext();
   envContext = (Context) initContext.lookup("java:comp/env");
   search = (SearchProvider)envContext.lookup("SHOWmail/search");

我靠谱javax.naming.NameNotFoundException: No object bound to name java:SHOWmail/search。我的工厂和 class 没有动过(如果需要会添加)。

非常感谢指出我哪里出错了。

看来我误解了这里netbeans/glassfish组合中不同的JNDI命名空间。

解决方法是在java:app下查找而不是在java:comp/env下查找;这会搜索 WEB-INF/glassfish-resources.xml.

web.xml

<resource-env-ref>
    <resource-env-ref-name>SHOWmail/search</resource-env-ref-name>
    <resource-env-ref-type>com.example.SearchProviderFactory</resource-env-ref-type>
</resource-env-ref>

glassfish-resources.xml

<custom-resource jndi-name="java:app/SHOWmail/search" res-type="com.example.ElasticSearchProvider" factory-class="com.example.SearchProviderFactory">
</custom-resource>