1
我想用Spring來使用MongoDB。 我想在我的DAO主類中注入一個MongoDbFactory。有彈簧的MongoDb工廠
我不想使用MongoTemplate,因爲我需要當我嘗試運行JUnit測試,測試我DAO類使用MongoDB的驅動
,我得到一個NullPointerExeption我廠....
我認爲這是我注射時的問題。
我的應用程序,配置:
<bean id="mongoFactoryBean" class="org.springframework.data.mongodb.core.MongoFactoryBean">
<property name="host" value="127.0.0.1" />
<property name="port" value="27017"/>
</bean>
<bean id="mongoDbFactory"
class="org.springframework.data.mongodb.core.SimpleMongoDbFactory">
<constructor-arg name="mongo" ref="mongoFactoryBean" />
<constructor-arg name="databaseName" value="agence_voyage" />
</bean>
<bean id="dao" class="dao.daoImpl.DaoImpl">
<property name="mongoFactory" ref="mongoDbFactory" />
</bean>
我DAO類:
public class DaoImpl implements Dao {
private MongoDbFactory mongoFactory;
private DB db;
@Required
public void setMongoFactory(MongoDbFactory myMongoFactory){
this.mongoFactory= myMongoFactory;
}
//TODO development mongodb://localhost
public void connect() throws UnknownHostException {
try{
this.db = mongoFactory.getDb("agence_voyage"); //NullPointer here
}
catch(DataAccessException d){
System.out.println(d);
}
}
public int getVoyageCount(String collection) {
DBCollection col = db.getCollection(collection);
return (int) col.count();
}
}
然後我的小測試:
public class TestDao {
@Test
public void test() {
Dao test = new DaoImpl();
try {
test.connect();
} catch (UnknownHostException e) {
System.out.println(e);
assertTrue(false);
}
assertTrue(test.getVoyageCount("voyage")== 1);
}
}
你有解決方案嗎? 我敢肯定,這是一個白癡的錯誤,但我找不到它!
在此先感謝!
好吧,你知道我需要導入哪些依賴關係,因爲我在SpringJUnit4Clas上得到錯誤...並且@ContextConfiguration似乎不存在。 – Lombric
@ user2323241它們是'spring-test'的一部分。你可以得到它[這裏](http://mvnrepository.com/artifact/org.springframework/spring-test)。 –