2013-02-20 100 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