title: Programmatically creating a JNDI DataSource for Spring
body: <p>I have an existing Spring web-based application that has datasources defined using JNDI, and I'm trying to create a standalone app to use the beans. How can I create the JNDI entry and database properties programmatically in the standalone application?</p>
  
  <pre><code>&lt;bean id="myDataSource" class="org.springframework.jndi.JndiObjectFactoryBean"&gt;
      &lt;property name="jndiName" value="java:comp/env/jdbc/MyDS" /&gt;
  &lt;/bean&gt;
  
      public static void main(String[] args) {
  
        // this throws an error since the JNDI lookup fails - can I programmatically define the database properties here?
  
      ClassPathXmlApplicationContext ctx = new  ClassPathXmlApplicationContext("applicationContext.xml");
  
      UserService userService = ctx.getBean(UserService.class);
      User user = userService.findUserById("jdoe");
  
      System.out.println("display name: " + user.getDisplayName());
  }
  </code></pre>
  
  <p>EDIT:</p>
  
  <p>I tried something like this, but am now getting the error "javax.naming.NoInitialContextException: Need to specify class name in environment or system property"</p>
  
  <pre><code>public static void main(String[] args) {
      setupJNDI();
  
      ClassPathXmlApplicationContext ctx = new  ClassPathXmlApplicationContext("applicationContext.xml");
  
      UserService userService = ctx.getBean(UserService.class);
      User user = userService.findUserById("jdoe");
  
      System.out.println("display name: " + user.getDisplayName());
  }
  
  
  private static void setupJNDI() {
      InitialContext ic;
      try {
          ic = new InitialContext();
          ic.createSubcontext("java:");
          ic.createSubcontext("java:/comp");
          ic.createSubcontext("java:/comp/env");
          ic.createSubcontext("java:/comp/env/jdbc");
          SQLServerConnectionPoolDataSource myDS = new SQLServerConnectionPoolDataSource();
          opaDS.setServerName("myserver");
          opaDS.setPortNumber(1433);
          opaDS.setUser("user");
          opaDS.setPassword("password");
  
          ic.bind("java:/comp/env/jdbc/MyDS", myDS);
      } catch (NamingException e) {
          e.printStackTrace();
      }
  }
  </code></pre>