Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No bean named 'mongoTemplate' available. Spring Boot + MongoDB

I'm building a backend using Spring Boot and MongoDB, first I'm making the user repository, service, and controller, and getting this error:

***************************
APPLICATION FAILED TO START
***************************

Description:

Field userRepository in com.package.package.controller.UserController required a bean named 'mongoTemplate' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)


Action:

Consider defining a bean named 'mongoTemplate' in your configuration.

Here's the code:

UserController:

package com.package.package.controller;

import com.package.package.entities.User;
import com.package.package.repositories.UserRepository;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserRepository userRepository;

    @GetMapping(value = "/")
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    @GetMapping(value = "/{id}")
    public User getUserById(@PathVariable("id") ObjectId id) {
        return userRepository.findBy_id(id);
    }

    @PutMapping(value = "/{id}")
    public void modifyUserById(@PathVariable("id") ObjectId id, @Valid @RequestBody User user) {
        user.set_id(id);
        userRepository.save(user);
    }

    @PostMapping(value = "/")
    public User createUser(@Valid @RequestBody User user) {
        user.set_id(ObjectId.get());
        userRepository.save(user);
        return user;
    }

    @DeleteMapping(value = "/{id}")
    public void deleteUser(@PathVariable ObjectId id) {
        userRepository.delete(userRepository.findBy_id(id));
    }
}

UserRepository:

package com.package.package.repositories;

import com.package.package.entities.User;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRepository extends MongoRepository<User, String> {
    User findBy_id(ObjectId _id);
}

UserService:

package com.package.package.service;

import com.package.package.entities.User;
import org.bson.types.ObjectId;

import java.util.List;

public interface UserService {
    User save(User user);
    User findbyid(ObjectId _id);
    List<User> getAll();
    void delete(User user);
}

MainApplication:

package com.package.package;

import com.package.package.repositories.UserRepository;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

@SpringBootApplication
@EnableMongoRepositories(basePackageClasses = UserRepository.class)
public class TestApplication {

    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }

}

I am using as a reference a past project that I made (the difference is that this was done with postgres). Any other information you want, just tell me. Thanks in advance.

UPDATE: Here's the pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.wazzka</groupId>
    <artifactId>wazzka</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>wazzka</name>
    <description>WazzkaProject</description>

    <properties>
        <java.version>14</java.version>
        <spring.framework.version>5.2.8.RELEASE</spring.framework.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-mongodb</artifactId>
            <version>3.0.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-releasetrain</artifactId>
            <version>Lovelace-SR9</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-commons</artifactId>
            <version>2.2.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>jakarta.validation</groupId>
            <artifactId>jakarta.validation-api</artifactId>
            <version>2.0.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>2.2.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
    </dependencies>

    <repositories>
        <repository>
            <id>spring-milestone</id>
            <name>Spring Maven MILESTONE Repository</name>
            <url>https://repo.spring.io/libs-milestone</url>
        </repository>
    </repositories>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
like image 429
Benjamín Paolo Díaz García Avatar asked Aug 12 '20 23:08

Benjamín Paolo Díaz García


People also ask

What is MongoTemplate spring boot?

The MongoTemplate class is the primary implementation of mongo-operations interface which specifies the basic set of MongoDB operations. We can also use MongoRepository interface to perform MongoDB operations. The implementation class of MongoRepository uses MongoTemplate bean at run time.

Which is better MongoTemplate or MongoRepository?

So I'd say that MongoTemplate is a better option, unless you have a very elaborated POJO model or need the custom queries capabilities of MongoRepository for some reason. Good points/examples. However your race condition example and undesired result can be avoided using @Version to prevent that very scenario.

Can we connect MongoDB with spring boot?

It's Easy to Connect MongoDB Atlas with Spring Boot Through this article, we demonstrated that MongoDB Spring Boot integration is easy using: Starter data MongoDB artifactid (the dependency we added while creating the Spring Initializr project) in pom. xml. A property on application.

Can we use JPA repository for MongoDB?

Yes, DataNucleus JPA allows it, as well as to many other databases.

Is there a Bean named 'mongotemplate' available?

java - No bean named 'mongoTemplate' available. Spring Boot + MongoDB - Stack Overflow No bean named 'mongoTemplate' available. Spring Boot + MongoDB I'm building a backend using Spring Boot and MongoDB, first I'm making the user repository, service, and controller, and getting this error:

What is mongotemplate in Spring Boot?

What is MongoTemplate? MongoTemplate is nothing but a Java class that comes under org.springframework.data.mongodb.core package. It provides a set of rich features for interacting with MongoDB and acts as a central class for Spring’s MongoDB support. Moreover, MongoTemplate is thread-safe and can be reused across multiple instances.

Does spring spring support MongoDB?

Spring also provides connectors like MongoTemplate and MongoRepository to perform all the database operations in MongoDB. What is Spring Boot used for? Spring Boot framework is used to create production-ready web applications with default configurations.

How do I create a bean for a bound MongoDB service?

When Connectors detects a bound MongoDB service, it should create a MongoDbFactory bean using the information from VCAP_SERVICES. This overrides the Boot autoconfiguration that creates a MongoDbFactory bean using properties if none is found. The MongoTemplate bean is always created by Boot.


2 Answers

Try adding this dependency:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
like image 122
Or Assayag Avatar answered Oct 16 '22 14:10

Or Assayag


While this is certainly not the reason for the error in most cases, the fact that it happened to me and I spent a fair amount of time looking for the reason made me want to post "the solution" here.

In my case I forgot to remove these lines again after disabling autoconfiguration initially (application.yml):

spring.autoconfigure.exclude:
  - org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration
  - org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration
like image 2
Martin Niederl Avatar answered Oct 16 '22 14:10

Martin Niederl