【问题标题】:Instantiate Spring MongoRepository manually手动实例化 Spring MongoRepository
【发布时间】:2013-05-12 08:00:49
【问题描述】:
我正在尝试使用embeddedMongoDb 测试我的 spring 数据 mongodb 存储库,它们是从 MongoRepository 扩展的接口。就像tutorial 一样,我想创建不使用 spring 应用程序上下文的测试,如果我在我的存储库类中使用普通的 mongoTemplate,这是可以实现的。
那么是否可以通过使用提供的实用方法传递 Mongo 和 MongoTemplate 实例来实例化 MongoRepository 接口实现。我假设 spring 在启动时会自动执行此操作。
【问题讨论】:
标签:
spring
integration-testing
spring-data-mongodb
【解决方案1】:
据我了解,您想在不使用 xml 配置的情况下测试您的应用程序。和你的教程一样,你的应用程序上下文在 java 类或 xml 文件中的配置最终是相同的。
对于我的测试,我个人使用 Junit 并像这样调用我的 xml 配置:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:META-INF/spring/applicationContext-mongo.xml"})
public class LicenseImplTest extends AbstractJUnit4SpringContextTests {
// Inject all repositories:
@Autowired
private IMyRepository myRepository;
}
例如,在我的 applicationContext-mongo.xml 中,我有:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<bean id="applicationProperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:META-INF/spring/database.properties"></property>
</bean>
<mongo:db-factory dbname="${mongo.database}" host="${mongo.host}" id="mongoDbFactory" port="${mongo.port}" write-concern="SAFE" />
<mongo:repositories base-package="fullpackage.repositories" />
<!-- To translate any MongoExceptions thrown in @Repository annotated classes -->
<context:annotation-config />
<bean class="org.springframework.data.mongodb.core.MongoTemplate" id="mongoTemplate">
<constructor-arg ref="mongoDbFactory" />
</bean>
</beans>
:
<mongo:repositories base-package="fullpackage.repositories" />
当找到注解@Autowired时,允许spring自动实例化你的仓库。
更简单,更恰当。就个人而言,我更喜欢这种方法。