2013-02-20 45 views
5

我有一个现有的基于Spring的基于Web的应用程序,它具有使用JNDI定义的数据源,我试图创建一个独立的应用程序来使用bean。如何在独立应用程序中以编程方式创建JNDI条目和数据库属性?以编程方式为Spring创建JNDI数据源

<bean id="myDataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> 
    <property name="jndiName" value="java:comp/env/jdbc/MyDS" /> 
</bean> 

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

编辑:

我想这样的事情,但我现在得到的错误“javax.naming.NoInitialContextException:需要环境或系统属性指定的类名”

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

回答

5

org.springframework.test依赖项支持通过SimpleNamingContextBuilder

// First create the mock JNDI tree and bind the DS 
SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder(); 
DataSource ds = new ComboPooledDataSource(); 
ds.setDriverClass(...); // etc. for uid, password, url 
builder.bind("java:comp/env/jdbc/MyDS" , ds); 
builder.activate(); 

// Then create the Spring context, which should now be able 
// to resolve the JNDI datasource 
ApplicationContext context = new ClassPathXmlApplicationContext("..."); 

这应该工作。

干杯,

+0

谢谢...我来试试 – acvcu 2013-02-20 14:39:33

+0

我试过,但我得到的错误“异常线程‘main’org.springframework.beans.factory.BeanCreationException:错误创建名称为豆”在类路径资源[applicationContext.xml]中定义的myDataSource:调用init方法失败;嵌套异常是javax.naming.NoInitialContextException:需要在环境或系统属性中指定类名称,或作为applet参数或应用程序资源文件中指定类名称:java.naming.factory.initial' – acvcu 2013-02-20 14:46:56

+0

我的坏,JNDI树应该在创建Spring上下文之前创建并激活课程 - 我已经编辑了相应的答案。 – 2013-02-20 15:50:54

相关问题