9

I am trying to connect mongoDb with Spring's mongoTemplate. I also tried changing version of 'spring-data-mongodb' from 1.7.2.RELEASE to 1.8.2.RELEASE, but even that didn't work.

Below is my code as used in the project.

Here's my 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>

My SpringMongoConfig file

    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");
    }

This is my main class

    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
  • You've probably got a version conflict between the dependency being pulled in by Spring Boot and the direct Spring Data dependency. Try grabbing the latest release version of each of them.
    – nbrooks
    Oct 18, 2016 at 5:09
  • already done that....no luck
    – anukuls
    Oct 18, 2016 at 5:13
  • 2
    Actually, you probably don't need the spring-data-mongodb dependency at all, since Spring Boot should pull that in. Try removing that.
    – nbrooks
    Oct 18, 2016 at 5:56

3 Answers 3

13

You only need below dependency and it will bring you all needed jars.

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

The error java.lang.NoSuchMethodError you are getting is for ClassTypeInformation class. Please check whether spring-data-commons-1.12.3.RELEASE.jar is present after you build your project. If not, then try cleaning up your build environment and update maven project.

4

A little late to the party, but here is what you need.

If you are trying to use a custom data manipulation rather than using the default inbuilt mongo repositories, then you need a mongoTemplate (kind of jdbc template but lets you define your own implementation of the client, i.e, the mongo client , in this case) and optionally mongoOperations on top of it(Mongo Operations is kind of a wrapper on top of the mongoTemplate)

You need the following dependencies - 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.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)
//  }
    
    
}

This should successfully create the mongoTemplate and mongoOperations and you should be able to make use of them in your DAO or service and access them.

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);
        }
        
    }
3
  • 1
    Please go through the MongoAutoConfiguration class file once to get an idea of what beans are required Feb 4, 2019 at 15:08
  • 2
    Thanks dude, you saved me!!
    – Sobhan
    May 10, 2020 at 11:24
  • :) great to know it helped May 11, 2020 at 7:01
0

I know it's not a technically justified solution. But after trying several alternatives, I just closed Eclipse and deleted all the .m2 folder content. Then, I retried to import the Project ina new Workspace and compiled. Surprise! This time it worked :) Sometimes rebooting works ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.