1

我有一个我们在 Jboss 中部署的现有服务 bean。不幸的是,它的数据源引用被配置为通过 JNDI 服务的“mappedName”查找注入数据源引用。

@Resource(name = "dataSource", mappedName = "java:/OracleDS")
private DataSource dataSource = null;

我想在非 JNDI 环境中测试 bean。当我在非 JNDI 环境中运行时,我希望得到这个异常。

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating 
bean with name 'myService': Injection of resource fields failed; nested exception 
is org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean 
definition with name 'java:/OracleDS' defined in JNDI environment: JNDI lookup 
failed; nested exception is javax.naming.NoInitialContextException: Need to 
specify class name in environment or system property, or as an applet parameter, 
or in an application resource file:  java.naming.factory.initial

我意识到解决这个问题的最快方法是删除 mappedName 限制,因为那时生产或测试 spring 上下文可以定义数据源。但在我不能这样做的情况下。有没有办法通过测试弹簧上下文定义 InitialContext 以避免上述异常。

4

1 回答 1

0

我对SimpleNamingContextBuilder做了更多阅读,并为我的测试用例提出了这个上下文设置。诀窍是使用 MethodInvokingFactoryBean 来确保调用 bind() 方法。

<bean id="jndiContext" class="org.springframework.mock.jndi.SimpleNamingContextBuilder" factory-method="emptyActivatedContextBuilder"/>

<bean id="invokingFactoryBean"
    class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="targetObject">
        <ref local="jndiContext" />
    </property>
    <property name="targetMethod">
        <value>bind</value>
    </property>
    <property name="arguments">
        <list>
            <value>java:/OracleDS</value>
            <ref bean="dataSource" />
        </list>
    </property>
</bean>

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${datasource.driverClassName}" />
    <property name="url" value="${datasource.url}" />
    <property name="username" value="${datasource.username}" />
    <property name="password" value="${datasource.password}" />
</bean>
于 2012-06-15T10:01:21.607 回答