1

I'm using jndi to perform a database lookup :

<jee:jndi-lookup id="myDataSource" jndi-name="jdbc/mydb"
        resource-ref="true" expected-type="javax.sql.DataSource" />

In a spring context file I invoke the constructor using :

<bean id="myController " class="com.MyController">
<constructor-arg index="0" ref="myDataSource" />
</bean>

I no longer want to expose "myDataSource" via a jndi lookup, so a I create a mock object which is of same type as "javax.sql.DataSource" and use it instead as a constructor parameter :

<bean id="myMockDataSource" class="com.mock.MyMockDataSourceConnection">
</bean>

<bean id="myController" class="com.MyController">
<constructor-arg index="0" ref="myMockDataSource" />
</bean>

The mock object just returns a dummy connection.

Is this the correct way so as to longer use jndi lookup when want to use a mock object instead ?

4

1 回答 1

0

您可能想查看 Spring 的SimpleNamingContextBuilder类,它对于构建 JNDI 树而不需要 Java EE 容器很有用。

class JndiMock
{
    public void init()
    {
        SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
        builder.bind( "jdbc/mydb" , new YourDummyConnectionClass() );
        builder.activate();
    }
...
}

(这是来自记忆,但应该给你的想法)。init-method您可以使用以下属性在应用程序上下文 XML 描述符中将其实例化为单例:

<bean id="jndimock" class="your.package.JndiMock" init-method="init" />

并使其在jee:jndi-lookup.

干杯,

于 2013-06-25T11:17:19.990 回答