java - Spring MVC 测试、JNDI

标签 java spring spring-mvc jndi spring-test

我想将现有数据源绑定(bind)到 JNDI 名称以进行测试。

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = { "file:WebContent/WEB-INF/application-context.xml",
        "file:WebContent/WEB-INF/test-datasource.xml" })
public class SimulatorTest {

    @Autowired
    @Qualifier("dataSource")
    private DataSource dataSource;

    @PostConstruct
    public void createContext() throws NamingException {
        SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
        builder.bind("java:comp/env/jdbc/DefaultDB", dataSource);
        builder.activate();
    }
...

这似乎有效,但一旦我的代码(即 EclipseLink)尝试查找此 JNDI 名称,它就会失败:

Exception Description: Cannot acquire data source [java:comp/env/jdbc/DefaultDB].
Internal Exception: javax.naming.OperationNotSupportedException: SimpleNamingContext does not support [javax.naming.Name]

我查看了源代码,确实没有:https://github.com/spring-projects/spring-framework/blob/master/spring-test/src/main/java/org/springframework/mock/jndi/SimpleNamingContext.java#L225-L293

如何创建上下文,以便 EclipseLink 不会无法查找数据源?

最佳答案

解决了我的问题。只是避免在测试期间使用 JNDI,至少许多人也是这么建议的。

在我的代码中,我手动创建了一个 EntityManagerFactory 来查找 persistence.xml 中定义的 JNDI 字符串。由于缺少 JNDI,此操作在测试期间失败。

现在,我让 Spring 为我创建 EntityManagerFactory,并让 Spring 选择数据源。

<bean id="entityManagerFactory"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="persistenceUnitName" value="MyPU" />
    <property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
    <property name="jpaDialect">
        <bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaDialect" />
    </property>
    <property name="jpaPropertyMap">
        <props>
            <prop key="eclipselink.logging.level">INFO</prop>
            <prop key="eclipselink.weaving">false</prop>
        </props>
    </property>
</bean>

<jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/DefaultDB" expected-type="javax.sql.DataSource" />

不在 persistence.xml 中定义数据源的 JNDI 名称,而是在 Spring 配置中定义,其优点是 Spring 可以在测试期间覆盖 dataSource bean - 所以现在 JNDI 查找,不会出现失败的测试。

关于java - Spring MVC 测试、JNDI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34803291/

相关文章:

java - android 崩溃报告中的奇怪堆栈

java - 从 Spring 应用程序运行 PhantomJS 来获取网页缩略图

java - 我可以通过自定义方法对用户进行身份验证吗?

java - 提交包含对象和多部分文件数据的表单

java - 检查正则表达式是否与可选组匹配

java - 模拟Mvc。如何在junit测试中涉及自定义对象

java - 1除以x时的余数运算符java

spring - 将 Proguard 与按名称使用 Spring @Autowired 的库一起使用

xml - 无法读取架构文档 'classpath:spring-beans-3.1.xsd'

spring - 如何在spring mvc中的两个 Controller 之间传递对象?