我想将现有数据源绑定(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]
如何创建上下文,以便 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/