java - 如何在 spring 中以声明方式将(绑定(bind))对象放入 jndi?

标签 java spring configuration jndi

我们有一个普通的独立 spring 应用程序,我们需要将 jdbc 数据源放在 jndi 中。 (我们使用 jboss treecache,它需要数据源在 jndi 中)。

一些谷歌搜索发现大多数 jndi-lookup 示例都使用 spring,其中对象已经放入 jndi(通过 tomcat 或应用程序服务器等),但我们需要其他方式:我有一个普通数据源 Spring bean,我将其注入(inject)其他服务,但我无法将它注入(inject) TreeCache,因为它只需要来自 jndi 的它。

找到org.springframework.jndi.JndiTemplate,可以声明为bean,例如:

<bean id="fsJndiTemplate" class="org.springframework.jndi.JndiTemplate">
    <property name="environment">
        <props>
            <prop key="java.naming.factory.initial">com.sun.jndi.fscontext.RefFSContextFactory</prop>
            <prop key="java.naming.provider.url">file:///c:\windows\temp</prop>
        </props>
    </property>
</bean>

但是除了在 java 代码中没有找到如何绑定(bind)它:fsJndiTemplate.bind(name, obj) 来自其他一些 bean 的初始化方法。 有没有办法以声明方式做到这一点?

最佳答案

感谢您的提问。我编写了 Treydone 解决方案的一个变体,并认为在此处提供实际代码可能会有用(因为它非常短):

public class JndiExporter implements InitializingBean {

    private final JndiTemplate template = new JndiTemplate();

    private Map<String, Object> jndiMapping = null;

    @Override
    public void afterPropertiesSet() throws Exception {
            for(Entry<String, Object> addToJndi: jndiMapping.entrySet()){
                    template.bind(addToJndi.getKey(), addToJndi.getValue());
            }
    }

    public void setJndiMapping(Map<String, Object> jndiMapping) {
            this.jndiMapping = jndiMapping;
    }

}

请注意,我实现了 InitializingBean 而不是 BeanFactoryAware。这允许这样的配置(带有引用):

<bean id="jndiExporter" class="com.ra.web.util.JndiExporter">
    <property name="jndiMapping">
        <map>
            <entry key="bean1" value-ref="other_spring_bean_id" />
            <entry key="bean2" value="literal_value" />
        </map>
    </property>
</bean>

关于java - 如何在 spring 中以声明方式将(绑定(bind))对象放入 jndi?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5974779/

相关文章:

java - Google App Engine 中的 e.printStackTrace

java - 如何在 Spring Boot 项目 : 上正确配置 Intellij IDEA 中的 jRebel

javascript - 将值从 Controller 传递到模态页面

java - Intellij 项目 View : not show multiple classes in same file

xml - uWSGI xml/ini 配置选项

java - 无法发送帖子请求

java - 在 Java 中将对象写入文件时内存不足

.net - 我什么时候应该将配置数据存储在数据库中而不是 web.config 中?

java - VTD-XML XPath 正在跳过前 3 条记录

java - 来自 xml 的 Spring Context 类加载器