Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

We have a plain standalone spring application and we need to put jdbc datasource in jndi. (we use jboss treecache and it need datasource to be in the jndi).

Some googling found most of all jndi-lookup examples with spring, where an object is already put in jndi (by tomcat or application server etc), but we need otherwise: I have a plain datasource Spring bean, which I inject to other services, but I can't inject it to TreeCache, because it needs it only from jndi.

Found org.springframework.jndi.JndiTemplate, which can be declared as bean, e.g.:

<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:windowsemp</prop>
        </props>
    </property>
</bean>

but not found how to bind with it other than in java code: fsJndiTemplate.bind(name, obj) from init-method of some other bean. Is there any way to do it declaratively?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
306 views
Welcome To Ask or Share your Answers For Others

1 Answer

Thanks for the questions. I wrote a variant of Treydone's solution and thought it might be useful to have actual code here (as it's pretty short):

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;
    }

}

Note that I implemented InitializingBean instead of BeanFactoryAware. This allows a configuration (with references) like this:

<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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...