2013-02-20 9 views
5

私はJNDIを使用して定義されたデータソースを持つ既存のSpring Webベースアプリケーションを使用していますが、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()); 
} 

EDIT: ":環境やシステムプロパティでクラス名を指定する必要が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

おかげで...私はこれを試みたが、 "スレッド『メイン』org.springframework.beans.factory.BeanCreationExceptionに例外:名前の作成中にエラーが発生しましBeanのエラーを取得しています – acvcu

+0

それを試してみましょうクラスパスのリソース[applicationContext.xml]で定義されているmyDataSource:initメソッドの呼び出しに失敗しました。ネストされた例外はjavax.naming.NoInitialContextExceptionです:環境またはシステムのプロパティ、アプレットのパラメータ、またはアプリケーションリソースファイルにクラス名を指定する必要があります。java.naming.factory.initial ' – acvcu

+0

JNDIツリーはもちろん、Springのコンテキストを作成しようとする前に作成してアクティブにする必要があります - 私はそれに応じて答えを編集しました。 –