Announcement Announcement Module
No announcement yet.
Programmatic use of JndiObjectFactoryBean fails Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Programmatic use of JndiObjectFactoryBean fails

    Hello everyone,

    I'm trying to programmatically use a JndiObjectFactoryBean to instantiate Tomcat Resources (in fact, javax.sql.DataSource), as the application I'm working on has a dynamic number of SQL databases it connects to (either through standard JDBC or through a ApplicationServer JNDI resource).

    I'm using the XML configuration for the JOFB for the central database, which works fine:

             <bean id="userCentralDatasource" class="org.springframework.jndi.JndiObjectFactoryBean">
    		<property name="resourceRef">
    		<property name="jndiName">
    I have another JNDI resource configured, and the following fails (getObject() returns null and thus the JdbcTemplate cannot be instantiated - JdbcTemplate.afterPropertiesSet() throws an exception of course):

    JndiObjectFactoryBean jofb = new JndiObjectFactoryBean();
    database = new JdbcTemplate((DataSource) jofb.getObject());
    However, this code works just fine, which is doing a manual JNDI lookup:
      context = new InitialContext();
      database = new JdbcTemplate((DataSource) context.lookup("java:comp/env/" + databaseConnectionInfo.getJndiName()));
    } catch (NamingException exception) {
    I've tried the JOFB instantation with different combinations of prefixing my JNDI name with java:comp/env/ and setting resourceRef to false, but to no avail.

    I seem to be missing something obvious, but I'm out of ideas right now. Of course, I could just do it without spring like in the 2nd example, but even if it would be the better choice, I'd like to know why the programmatic JOFB use fails for me.

    Thanks in advance

    ~ Nils

  • #2
    Why use the factory bean for a lookup?! Use the JndiTemplate for that there is no need or added value in using the JndiObjectFactoryBean programmatically. But if you must first call the afterPropertiesSet method before calling getObject to properly initialize the FactoryBean.


    • #3
      Thanks, I've switched to using the JNDITemplate - I was assuming that if I set resourceRef to true, the JOFB might do some preparations to the query, that the JNDITemplate does not.

      Using the JNDITemplate works like a charm and the code is even shorter. Thank you very much.