spring data mongo repository为null

时间:2014-02-27 14:22:48

标签: java spring-data-mongodb

我正在编写一个独立的java程序,它可以调用spring数据存储库来进行整理。我正在使用mongo db进行持久化。我正在关注stackoverflow帖子和来自github的一些项目,但是当我运行我的程序时它因为存储库为空而失败。我不是春天的专家,所以如果有人能告诉我发布的程序的问题会很有帮助。

应用程序的context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mongo="http://www.springframework.org/schema/data/mongo"
    xsi:schemaLocation="http://www.springframework.org/schema/data/mongo 
    http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
    http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd">


<mongo:mongo id="mongo" host="monopolyvm3" port="27017" />
<mongo:db-factory dbname="test" mongo-ref="mongo" />
<mongo:db-factory id="mongoDbFactory" dbname="cloud"
    mongo-ref="mongo" />


<bean id="mappingContext" class="org.springframework.data.mongodb.core.mapping.MongoMappingContext" />

<bean id="defaultMongoTypeMapper"
    class="org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper">
    <constructor-arg name="typeKey"><null/></constructor-arg>
</bean>

<bean id="mappingMongoConverter" class="org.springframework.data.mongodb.core.convert.MappingMongoConverter">
    <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
    <constructor-arg name="mappingContext" ref="mappingContext" />
    <property name="typeMapper" ref="defaultMongoTypeMapper" />
</bean>

<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    <constructor-arg ref="mongoDbFactory" />
    <constructor-arg name="mongoConverter" ref="mappingMongoConverter" />
    <property name="writeConcern" value="SAFE" />
</bean>
<context:component-scan base-package="com.xxxx"></context:component-scan>

<mongo:repositories base-package="com.xxxx.yyyy" />

存储库

public interface SlpRepository extends MongoRepository<Slp, Long> {

}

主程序

public class App {

    @Autowired
    static
    SlpRepository slpRepository;
    public static void main(String[] args) {
        ApplicationContext ctx = new GenericXmlApplicationContext("application-context.xml");
        Slp slp = new Slp();
        slp.setClientCount(100000L);
        slp.setPolicyName("testing");
        slp.setSlpName("slp_testing");
        slpRepository.save(slp);

    }


}

Object to store
------------------

@Document(collection="slps")
public class Slp implements Serializable {


    private Long slpId;
    private String slpName;
    private String policyName;
    private Long clientCount;
}
.....all getters and setters

JFYI ..我试图使用mongotemplate保存对象并且效果很好。

1 个答案:

答案 0 :(得分:0)

此示例中的问题是您在App类中创建上下文但从未从应用程序上下文获取存储库的句柄。您无法自动连接到包含应用程序上下文的同一个类。您可以尝试从上下文中获取存储库的实例(即ctx.getBean(SlpRepository.class))。