6

JNDI を使用して定義されたデータソースを持つ既存の Spring Web ベースのアプリケーションがあり、Bean を使用するスタンドアロン アプリを作成しようとしています。スタンドアロン アプリケーションで 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();
    }
}
4

1 に答える 1

6

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( "..." );

それはうまくいくはずです。

乾杯、

于 2013-02-20T14:29:17.177 に答える