【问题标题】:MongoDb Factory with spring带弹簧的 MongoDb 工厂
【发布时间】:2014-01-14 16:22:23
【问题描述】:

我想在 Spring 中使用 MongoDB。 我正在尝试在我的 DAO 主类中注入 MongoDbFactory。

我不想使用 MongoTemplate,因为我需要使用 MongoDB-Driver

当我尝试运行 jUnit 测试以测试我的 DAO 类时,我的工厂出现 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);
}

}

你有什么解决办法吗? 我确定这是一个白痴错误,但我没有找到它!

提前致谢!

【问题讨论】:

    标签: java spring mongodb spring-mvc dependency-injection


    【解决方案1】:

    您的测试似乎没有以任何方式连接到 Spring 上下文。您实际上是自己创建对象而不是获取 Spring 托管 bean

    Dao test = new DaoImpl();
    

    为什么 Spring 会对这个对象做任何事情?

    将这些注释添加到您的课程中

    @ContextConfiguration(locations = "yourfile.xml")
    @RunWith(SpringJUnit4ClassRunner.class)
    

    并直接注入DaoImpl bean。

    @Autowired
    private Dao test;
    

    然后在你的测试中使用它。

    阅读 Spring 文档中的 chapter on unit testing

    【讨论】:

    • 好的,你知道我需要导入哪些依赖项,因为我在 SpringJUnit4Clas 上遇到错误......而且@ContextConfiguration 似乎没有退出。
    • @user2323241 他们是spring-test 的一部分。你可以得到它here
    猜你喜欢
    • 2018-01-24
    • 1970-01-01
    • 2017-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-21
    相关资源
    最近更新 更多