在通过Spring连接mongodb时创建名为'mongoTemplate'的bean时出错

时间:2016-10-18 04:58:34

标签: java spring mongodb mongotemplate

我正在尝试将mongoDb与Spring的mongoTemplate连接起来。我也尝试将'spring-data-mongodb'的版本从1.7.2.RELEASE更改为1.8.2.RELEASE,但即便如此也没有用。

以下是我在项目中使用的代码。

这是我的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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.storeApp</groupId>
    <artifactId>storeApp</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>Store Application</name>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.1.RELEASE</version>
    </parent>

    <dependencies>
        <!-- <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency> -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-mongodb</artifactId>
            <version>1.7.2.RELEASE</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>storeApp</finalName>
    </build>
    <repositories>
        <repository>
            <id>spring-releases</id>
            <name>Spring Releases</name>
            <url>https://repo.spring.io/libs-release</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-releases</id>
            <name>Spring Releases</name>
            <url>https://repo.spring.io/libs-release</url>
        </pluginRepository>
    </pluginRepositories>

</project>

我的SpringMongoConfig文件

    package com.storeApp.config;

    import org.springframework.context.ApplicationContext;
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.data.mongodb.MongoDbFactory;
    import org.springframework.data.mongodb.core.MongoFactoryBean;
    import org.springframework.data.mongodb.core.MongoOperations;
    import org.springframework.data.mongodb.core.MongoTemplate;
    import org.springframework.data.mongodb.core.SimpleMongoDbFactory;

    import com.mongodb.MongoClient;

    @Configuration
    public class SpringMongoConfig1 {

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

        public @Bean
        MongoTemplate mongoTemplate() throws Exception{
            MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory());
            return mongoTemplate;
        }

    //  ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringMongoConfig.class);
    //  MongoOperations mongoOperation = (MongoOperations)ctx.getBean("mongoTemplate");
    }

这是我的主要课程

    package com.storeApp.core;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import com.storeApp.config.SpringMongoConfig1;
import com.storeApp.config.SpringMongoConfig2;
import com.storeApp.model.Store;

public class StoreMainApp {

    public static void main(String[] args) {

        ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringMongoConfig1.class);
        MongoOperations mongoOperation = (MongoOperations)ctx.getBean("mongoTemplate");

        Store store = new Store("Sample store 1", "Street 1", "City 1", (float) 35.4);
        System.out.println("into main method");
//      mongoOperation.save(store);
    }
}

Stacktrace:

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Oct 18, 2016 10:08:47 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: Cluster created with settings {hosts=[127.0.0.1:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
Oct 18, 2016 10:08:47 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:1, serverValue:12}] to 127.0.0.1:27017
Oct 18, 2016 10:08:47 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: Monitor thread successfully connected to server with description ServerDescription{address=127.0.0.1:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 2, 10]}, minWireVersion=0, maxWireVersion=4, maxDocumentSize=16777216, roundTripTimeNanos=1546838}
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoTemplate' defined in com.storeApp.config.SpringMongoConfig1: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.core.MongoTemplate]: Factory method 'mongoTemplate' threw exception; nested exception is java.lang.NoSuchMethodError: org.springframework.data.util.ClassTypeInformation.from(Ljava/lang/Class;)Lorg/springframework/data/util/ClassTypeInformation;
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1119)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1014)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
    at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:84)
    at com.storeApp.core.StoreMainApp.main(StoreMainApp.java:20)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.core.MongoTemplate]: Factory method 'mongoTemplate' threw exception; nested exception is java.lang.NoSuchMethodError: org.springframework.data.util.ClassTypeInformation.from(Ljava/lang/Class;)Lorg/springframework/data/util/ClassTypeInformation;
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
    ... 13 more
Caused by: java.lang.NoSuchMethodError: org.springframework.data.util.ClassTypeInformation.from(Ljava/lang/Class;)Lorg/springframework/data/util/ClassTypeInformation;
    at org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper.<clinit>(DefaultMongoTypeMapper.java:49)
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter.<init>(MappingMongoConverter.java:111)
    at org.springframework.data.mongodb.core.MongoTemplate.getDefaultMongoConverter(MongoTemplate.java:2039)
    at org.springframework.data.mongodb.core.MongoTemplate.<init>(MongoTemplate.java:217)
    at org.springframework.data.mongodb.core.MongoTemplate.<init>(MongoTemplate.java:202)
    at com.storeApp.config.SpringMongoConfig1.mongoTemplate(SpringMongoConfig1.java:25)
    at com.storeApp.config.SpringMongoConfig1$$EnhancerBySpringCGLIB$$81e5bc96.CGLIB$mongoTemplate$0(<generated>)
    at com.storeApp.config.SpringMongoConfig1$$EnhancerBySpringCGLIB$$81e5bc96$$FastClassBySpringCGLIB$$52d3ef2d.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:309)
    at com.storeApp.config.SpringMongoConfig1$$EnhancerBySpringCGLIB$$81e5bc96.mongoTemplate(<generated>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
    ... 14 more

Not getting where is the problem...

3 个答案:

答案 0 :(得分:3)

您只需要以下依赖性,它将为您带来所有需要的罐子。

 <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb</artifactId>
  </dependency>

您获得的错误java.lang.NoSuchMethodError适用于ClassTypeInformation课程。生成项目后,请检查 spring-data-commons-1.12.3.RELEASE.jar 是否存在。如果没有,那么尝试清理构建环境并更新maven项目。

答案 1 :(得分:1)

聚会晚了一点,但这就是您所需要的。

如果您尝试使用自定义数据操作而不是使用默认的内置mongo repositories,则需要使用mongoTemplate(某种jdbc模板,但可以定义自己的客户端实现,即mongo client,在其顶部还可以选择mongoOperationsMongo Operations有点像mongoTemplate顶部的包装器

您需要以下依赖项-pom.xml:

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>

 <!-- https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver -->
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
        </dependency>

MongoConfig.java

@PropertySource("classpath:application.properties")

public class MongoConfig{

    @Value("${spring.data.mongodb.host}")
    private String mongoHost;

    @Value("${spring.data.mongodb.port}")
    private String mongopPort;


        @Value("${spring.data.mongodb.port}")
        private String mongoPort;

        @Value("${spring.data.mongodb.database}")
        private String mongoDB;

        /*Client vs FactoryClient
         * 
         * Factory bean that creates the com.mongodb.MongoClient instance
         * 
         * Classes attributed with @repostiory may throw mongo related exceptions. Declaring an instance of MonogClientFactoryBean
         * helps in translating them to spring data exceptions which can then be caught using @ExceptionHandling

         public @Bean MongoClientFactoryBean mongo() throws Exception {
              MongoClientFactoryBean mongo = new MongoClientFactoryBean();
              mongo.setHost("localhost");
              MongoClientOptions clientOptions = MongoClientOptions.builder().applicationName("FeddBackAPI_DB")
                      .connectionsPerHost(2000)
                      .connectTimeout(4000)
                      //.maxConnectionIdleTime(1000000000)
                      .maxWaitTime(3000)
                      .retryWrites(true)
                      .socketTimeout(4000)
                      .sslInvalidHostNameAllowed(true)//this is very risky

                      .build();
              mongo.setMongoClientOptions(clientOptions);


              return mongo;
         }
}

DataSourceConfig.java

@Configuration
@Import(value=MongoClientFactory.class)
public class DataSourceConfig {

    @Autowired
    Mongo mongo;

    @Autowired
    Environment env;

    @Bean
    public String test() {
        System.out.println("mongo"+mongo);
        return "rer";
    }

    @Bean
    @Qualifier("customMongoTemplate")
public MongoTemplate mongoTemplate() {

        //MongoClient is the actual pool used by mongo. Create it using client factory then, autoclosing of threads are handled on its own
        MongoDbFactory factory = new SimpleMongoDbFactory((MongoClient) mongo, "mongo_test");
        MongoTemplate template = new MongoTemplate(factory);

        return template;
    }

    @Bean
    @Qualifier(value="customMongoOps")
    public MongoOperations mongoOps() {
        MongoOperations ops = mongoTemplate();
        return ops;
    }


    @Bean
    public MongoDbFactory factory() {
        MongoDbFactory factory = new SimpleMongoDbFactory((MongoClient) mongo, "mongo_test");
        return factory;
    }

//  @Bean
//  public GridFsTemplate gridFsTemplate() {
//      return new GridFsTemplate(mongo, converter)
//  }


}

这应该成功创建mongoTemplatemongoOperations,并且您应该能够在DAO或服务中使用它们并访问它们。

PersonService.java

   @Service
    public class PersonService {
        @Autowired
        private PersonRepository personRepo;

        @Autowired
        PersonSequenceServiceImpl seqService;

        @Autowired
        @Qualifier(value="customMongoOps")
        MongoOperations mongoOps;

        public List<Person> findAllPersons() {
            return personRepo.findAll();
        }

        public List<Person> createAndFindAllPersons() {
            Person p1 = new Person( "another1", "ll1", 30);
            Person p2 = new Person( "another2", "ll2", 30);

            if(!mongoOps.collectionExists(Person.class)) {
                mongoOps.dropCollection("Person_table");
            }
            //return personRepo.save(person);


            System.out.println("P1 data before inserting:"+p1);
            mongoOps.insert(Arrays.asList(p1,p2), Person.class);
            //mongoOps.dropCollection(Person.class);
            return mongoOps.findAll(Person.class);
        }

    }

答案 2 :(得分:0)

我知道这不是技术上合理的解决方案。但是尝试了几种选择之后,我只是关闭了Eclipse ,并删除了所有.m2文件夹内容。 然后,我尝试将项目导入新的工作区并进行编译。 惊喜!这次它起作用了:) 有时重新启动会起作用;)