1

我想尝试与 MongoDB 的弹簧集成,为此我做了以下事情。但它不工作一些如何 MongoTemplate 实例未创建并抛出 java.lang.NullPointerException。这是我的 application-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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">

  <!-- Activate annotation configured components -->
  <context:annotation-config/>

  <!-- Scan components for annotations within the configured package -->
  <context:component-scan base-package="com.jeroenreijn.mongodb.example">
    <context:exclude-filter type="annotation" expression="org.springframework.context.annotation.Configuration"/>
  </context:component-scan>

  <!-- Factory bean that creates the Mongo instance -->
  <bean id="mongo" class="com.mongodb.Mongo">
    <constructor-arg name="host" value="127.0.0.1" />
    <constructor-arg name="port" value="27017" />
  </bean>

  <!-- Define the MongoTemplate which handles connectivity with MongoDB -->
  <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate" depends-on="mongo">
    <constructor-arg name="mongo" ref="mongo"/>
    <constructor-arg name="databaseName" value="firstMongoDB"/>
  </bean>

  <!-- Use this post processor to translate any MongoExceptions thrown in @Repository annotated classes -->
  <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>

</beans>

这是我的主要方法:

public class MainApplication {

    /**
     * This is a variable used for Logging purpose, I have used slf4j.
     */
    final Logger LOGGER = LoggerFactory.getLogger(MainApplication.class);
    @Autowired
    MongoTemplate mongoTemplate;

    public void savePerson(Person p) {
        mongoTemplate.save(p);
    }

    public static void main(String[] args) {
        Person p = new PersonImpl("1", "Ayushya", "Devmurari");
        MainApplication ma = new MainApplication();
        ma.savePerson(p);
        ma.LOGGER.info("Person named : " + p.getName() + " with id : "
                + p.getId() + " is saved.");
    }

}

这是我的模型课:

@Document(collection = "AnotherPersonCollection")
public class PersonImpl implements Person {

    private String id;
    private String name;
    private String surname;

    // Constructor
    public PersonImpl() {

    }

    public PersonImpl(String id, String name, String surname) {
        this.id = id;
        this.name = name;
        this.surname = surname;
    }

    @Override
    public String getId() {
        return id;
    }

    @Override
    public void setId(String id) {
        this.id = id;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String getSurname() {
        return surname;
    }

    @Override
    public void setSurname(String surname) {
        this.surname = surname;
    }

    @Override
    public String toString() {
        return "Person has name " + "Id :" + id + "\n" + name + " \n"
                + "surname :" + surname;
    }

}

需要帮助我已经尝试了几个教程,例如 mkyong 和许多其他教程,并且我遇到了 NoBeanDefinitionFound 的“mongoTemplate”错误:所以我尝试了这个。

更新:这是我的 pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
    http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.discusit</groupId>
    <artifactId>MongoDBAppTrail4</artifactId>
    <packaging>jar</packaging>
    <version>1.0</version>
    <name>Trying to create MongoDBApp</name>
    <url>http://maven.apache.org</url>

    <dependencies>
        <!-- Log4J -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.5</version>
        </dependency>
        <!-- Spring framework -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>3.2.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>3.2.2.RELEASE</version>
        </dependency>

        <!-- Spring Web -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>3.2.2.RELEASE</version>
        </dependency>

        <!-- mongodb java driver -->
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>2.11.0</version>
        </dependency>
        <!-- Spring data mongodb -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-mongodb</artifactId>
            <version>1.2.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.2.2</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.0</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>true</downloadJavadocs>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

这是我的堆栈跟踪:

log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'mongoTemplate' is defined
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:568)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1102)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:278)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1117)
    at com.discusit.main.MainApplication.main(MainApplication.java:39)
4

4 回答 4

1

如前所述,您必须在主类中创建应用程序上下文。要使用自动装配,您可以将主类定义为 spring bean。

<?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"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

      <!-- your mongodb bean befinitions -->

      <bean class="fullpackage.MainApplication"/>

</beans>

然后在你的主类中获取实例

public class MainApplication {

/**
 * This is a variable used for Logging purpose, I have used slf4j.
 */
final Logger LOGGER = LoggerFactory.getLogger(MainApplication.class);

@Autowired
MongoTemplate mongoTemplate;

public void savePerson(Person p) {
    mongoTemplate.save(p);
}

public static void main(String[] args) {
    ApplicationContext ctx = new GenericXmlApplicationContext("application-context.xml");
    MainApplication ma = ctx.getBean(MainApplication.class);
    Person p = new PersonImpl("1", "Ayushya", "Devmurari");
    ma.savePerson(p);
    ma.LOGGER.info("Person named : " + p.getName() + " with id : " + p.getId() + " is saved.");
}

}
于 2013-05-21T07:55:03.860 回答
1

我看过@Aayush 解决方案。我发现了两个错误:

  • 您没有正确调用您的 xml 文件配置。

    之前

    ApplicationContext ctx = new GenericXmlApplicationContext("classpath*:application-context.xml");
    

    之后

    ApplicationContext ctx = new GenericXmlApplicationContext("classpath:META-INF/applicationContext.xml");
    
  • 您调用 ExceptionTranslationPostProcessor。为什么 ?此调用会导致错误。我删除了它。

    <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
    

所以最后,我用小的改动测试了你的应用程序,并且一切正常。不要忘记启动 mongodb 服务器并创建您的数据库“firstMongoDB”。有关更多信息,请在此处阅读:http: //docs.mongodb.org/manual/tutorial/getting-started/

我已经在 github 上发布了你的项目:https ://github.com/m-reka/spring-data-mongoTemplate

告诉我什么时候可以删除它:)

于 2013-05-21T14:36:11.413 回答
0

在您的主要方法中添加:

    ApplicationContext context = 
        new ClassPathXmlApplicationContext("application-context.xml"); //change xml path as you need.
    MMongoTemplate mongoTemplate=context.getBean(MMongoTemplate.class);

当您使用 main 方法时,它会跳过在 spring context 中加载 bean,因此 autowire 将不起作用。

于 2013-05-21T07:30:07.747 回答
0
use this way to configure mongodb


AppMongoConfig.class

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;

import com.mongodb.Mongo;

@Configuration
public class AppMongoConfig {

    public @Bean
    MongoDbFactory mongoDbFactory() throws Exception {
        return new SimpleMongoDbFactory(new Mongo(), "testing");
    }

    public @Bean
    MongoTemplate mongoTemplate() throws Exception {

        //remove _class
        MappingMongoConverter converter = new MappingMongoConverter(mongoDbFactory(), new MongoMappingContext());
        converter.setTypeMapper(new DefaultMongoTypeMapper(null));

        MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory(), converter);

        return mongoTemplate;

    }

}

/-------------------------------------------------------------------------------------------------/

testing-servlet.xml


<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mongo="http://www.springframework.org/schema/data/mongo"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc


http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
  http://www.springframework.org/schema/data/mongo
          http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd

http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">

    <bean
        class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

    <mongo:mongo host="testing" port="27017">

    <mongo:options connections-per-host="100"
   threads-allowed-to-block-for-connection-multiplier="5"
            max-wait-time="120000000"
            connect-timeout="10000000"
            socket-keep-alive="true"
            socket-timeout="15000000"
            auto-connect-retry="true"/>

    </mongo:mongo>


    <mongo:db-factory dbname="testing"
        mongo-ref="mongo" />
    <bean id="mongoTypeMapper"
        class="org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper">
        <constructor-arg name="typeKey">
            <null />
        </constructor-arg>
    </bean>
    <bean id="mongoMappingContext"
        class="org.springframework.data.mongodb.core.mapping.MongoMappingContext" />
    <bean id="mongoConverter"
        class="org.springframework.data.mongodb.core.convert.MappingMongoConverter">
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
        <constructor-arg name="mappingContext" ref="mongoMappingContext" />
        <property name="typeMapper" ref="mongoTypeMapper"></property>
    </bean>
    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
        <constructor-arg name="mongoConverter" ref="mongoConverter" />
        <property name="writeResultChecking" value="EXCEPTION" />
    </bean>

</beans>

/---------------------------------------------------------------------------/

@Autowired
    private MongoTemplate mongoTemplate ;

    @Override
    public String methodTesting(classname object) { //classname change to your class name
        String response="failer";
        try {
            if (!mongoTemplate.collectionExists(classname.class)) {
                mongoTemplate.createCollection(classname.class);
            }
            mongoTemplate.save(object);
            `response="success";`
        } catch (Exception e) {
            System.out.println("inside catch");
        e.printStackTrace();    // TODO: handle exception
        }
        return response;
    }
于 2015-01-27T05:45:03.710 回答