mongoTemplate bean could not be found - java

I am building a very simple Spring boot app with mvc + mongodb. I used Spring initializer to create the proj with web, thymeleaf and mongo dependencies. I have one controller, one model and a view but I keep on getting an error when trying to execute the app:
Description:
Field repo in com.example.CustomerController required a bean named 'mongoTemplate' that could not be found.
Action:
Consider defining a bean named 'mongoTemplate' in your configuration.
CustomerController:
import model.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* Created by Hello on 25/04/2017.
*/
#Controller
#RequestMapping("/home")
public class CustomerController {
#Autowired
CustomerMongoRepo repo;
#RequestMapping(value = "/home", method= RequestMethod.GET)
public String viewingHome(Model model){
//initDB();
model.addAttribute("key", "THIS IS FROM THE MODEL");
return "homepage";
}
}
CustomerMongoRepo:
import org.springframework.data.repository.CrudRepository;
import model.Customer;
public interface CustomerMongoRepo extends CrudRepository {}
MainApp:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
import org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration;
#SpringBootApplication(exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
public class DemoApplication extends WebMvcAutoConfiguration {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Customer Model:
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
/**
* Created by Hello on 25/04/2017.
*/
#Document(collection = "customerCollection")
public class Customer {
#Id
private int id;
private String fName;
private String sName;
public Customer(){}
public Customer(int id, String fName, String sName){
setfName(fName);
setsName(sName);
setId(id);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getsName() {
return sName;
}
public void setsName(String sName) {
this.sName = sName;
}
}
My Application Properties:
spring.data.mongodb.database=customer
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.uri=mongodb://localhost:27018/mydb
spring.data.mongo.repositories.enabled=true

You are excluding Mongo Configuration.
#SpringBootApplication(exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
Then how will spring create mongoTemplate for you. Remove this exclusion or create MongoTemplate manually and register it with application context(using #Bean)

I recently ran into this same problem and my solution was to remove spring-data-mongodb:
<!--<dependency>-->
<!-- <groupId>org.springframework.data</groupId>-->
<!-- <artifactId>spring-data-mongodb</artifactId>-->
<!-- <version>3.2.1</version>-->
<!--</dependency>-->
and I kept spring-boot-starter-data-mongodb:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
It is seen that either the two together gave conflict or I need to add 'something' that I did not know.
Happy code !!! And I hope to be of help to you
Update
Later I found something related to what could be described by the problem although I would never finish checking it:
https://stackoverflow.com/a/12389842/7911776

Related

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

Hello there I am new to spring boot, i am getting this error since a while, unfortunately can't fix it. I am googling since then but still not find what i did wrong. I believe the error exists in the Service Class. I tried to remove the field injection ( #Autowired) and implemented as a constructor injection but that did not work as well Find below my code:
Entity:
package com.devops.maven.cars_api_maven.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import javax.persistence.*;
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
#Entity
#Table(name = "CARS")
#SequenceGenerator(name="seq", initialValue=4, allocationSize=100)
public class Car {
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seq")
private Long id;
String manufacturer;
String model;
int build;
public Car() {
}
public Car(Long id, String manufacturer, String model, int build) {
this.id = id;
this.manufacturer = manufacturer;
this.model = model;
this.build = build;
}
public Long getId() {
return id;
}
public String getManufacturer() {
return manufacturer;
}
public String getModel() {
return model;
}
public int getBuild() {
return build;
}
public void setId(Long id) {
this.id = id;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public void setModel(String model) {
this.model = model;
}
public void setBuild(int build) {
this.build = build;
}
}
DAO
package com.devops.maven.cars_api_maven.repositories;
import com.devops.maven.cars_api_maven.model.Car;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface CarsRepository extends JpaRepository<Car, Long> {
}
Main
package com.devops.maven.cars_api_maven;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
#SpringBootApplication (
exclude = {DataSourceAutoConfiguration.class },
scanBasePackages={
"com.devops.maven", "com.devop.application"}
)
public class CarsApplication {
public static void main(String[] args) {
SpringApplication.run(CarsApplication.class, args);
}
}
Service Class
package com.devops.maven.cars_api_maven;
import com.devops.maven.cars_api_maven.model.Car;
import com.devops.maven.cars_api_maven.repositories.CarsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;
import java.util.List;
#RestController
#RequestMapping("cars")
#Service
public class CarsController {
#Autowired
private CarsRepository repository;
#GetMapping
public List<Car> getCars() {
return repository.findAll();
}
#PostMapping
public Car addCar(#RequestBody Car car) {
return repository.save(car);
}
#SuppressWarnings("deprecation")
#GetMapping(value = "/{id}")
public Car getCarById(#PathVariable("id") long id) {
return repository.getOne(id);
}
#DeleteMapping(value = "/{id}")
public void removeCarById(#PathVariable("id") long id) {
repository.deleteById(id);
}
}
Error output:
*************************** APPLICATION FAILED TO START
Description:
Field repository in com.devops.maven.cars_api_maven.CarsController
required a bean of type
'com.devops.maven.cars_api_maven.repositories.CarsRepository' 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 of type
'com.devops.maven.cars_api_maven.repositories.CarsRepository' in your
configuration.
Please remove exclude = {DataSourceAutoConfiguration.class } from below class and run again. It will fix the issue.
package com.devops.maven.cars_api_maven;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
#SpringBootApplication (
exclude = {DataSourceAutoConfiguration.class },
scanBasePackages={
"com.devops.maven", "com.devop.application"}
)
public class CarsApplication {
public static void main(String[] args) {
SpringApplication.run(CarsApplication.class, args);
}
}

REST API is always throwing 404 error in Spring boot maven multimodule project with H2 database

I am new to Spring boot and I have created a multi-module project(maven) with spring boot. And I created some REST APIs and connected to H2 database.
The database is connected successfully and able to run in localhost.
This is my project tree.. User-Management is parent and core, serverAPI are child modules. And I have created packages for each module and added the relevant classes.
I have tried everything I know and searched google for like 5 days but nothing worked for me. I have included every code I wrote here. Please help me to find what the issue is.
(I am using intellij idea 2020.3 ultimate)
User.java
package com.hms.usermanagement.core.model;
import javax.persistence.*;
#Entity
#Table(name = "users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(name = "full_name")
private String fullName;
#Column(name = "email")
private String email;
public User() {
}
public User(long id, String fullName, String email) {
this.id = id;
this.fullName = fullName;
this.email = email;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}}
UserRepository
package com.hms.usermanagement.core.repository;
import com.hms.usermanagement.core.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface UserRepository extends JpaRepository<User,Long> {
}
Application
package com.hms.usermanagement.serverAPI.application;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Application {
public static void main(String[] args){
SpringApplication springApplication = new SpringApplication(Application.class);
springApplication.run(args);
}}
UserController
package con.hms.usermanagement.serverAPI.controller;
import com.hms.usermanagement.core.model.User;
import com.hms.usermanagement.core.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
#RestController
#RequestMapping("/api")
public class UserController {
#Autowired
private UserRepository userRepository;
//Create Users
#PostMapping("/user")
public User createUser( #Validated #RequestBody User user){
return userRepository.save(user);
}
//View all Users
#GetMapping("/users")
public List<User> getAllUsers(){
return userRepository.findAll();
}
//Update Users
#PutMapping("/users/{id}")
public ResponseEntity <User> updateUser(#PathVariable(value = "id") long userId , #RequestBody User userDetails){
Optional<User> user = userRepository.findById(userId);
if(user.isPresent()){
User _user = user.get();
_user.setFullName(userDetails.getFullName());
_user.setEmail(userDetails.getEmail());
return new ResponseEntity<>(userRepository.save(_user), HttpStatus.OK);
}else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
//Delete Users
#DeleteMapping("/users/{id}")
public ResponseEntity<?> deleteUser(#PathVariable(value = "id") long userId){
userRepository.findById(userId);
userRepository.deleteById(userId);
return ResponseEntity.ok().build();
}
application.properties
spring.datasource.url=jdbc:h2:~/test
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
#enable H2 console
spring.h2.console.enabled=true
#custom H2 console
spring.h2.console.path=/h2
schema-h2.sql
CREATE TABLE users (id long PRIMARY KEY AUTO_INCREMENT, full_name VARCHAR(30), email VARCHAR(50));
I have tried using both these 2 urls
Even "id" field is auto generated but I tried to add id also using postman.. But still getting the same error
Your Sprint boot runner class, Application class is under com.hms.usermanagement.serverAPI.application package, so Spring boot will only scan the components under com.hms.usermanagement.serverAPI.application. So your core and web components are not recognized by Spring boot.
To solve the issue try to move Application.java class under com.hms.usermanagement.
Or you can customize the component scan by adding#ComponentScan annotation to Application.java class:
#SpringBootApplication
#ComponentScan(basePackages = "com.hms.usermanagement")
I did a new maven: mvn clean verify of the project and the issue was solved.
Remove #Validated and try #Valid as below
Calling with [LOCALHOST]:[PORT]/api/user
//Create Users
#PostMapping("/user")
public User createUser(#RequestBody #Valid User user){
return userRepository.save(user);
}

How can I make Autowired adnotation working?

I'm trying to learn spring using some internet courses. I have problem with #Autowired and I'm still getting Error: org.springframework.beans.factory.UnsatisfiedDependencyException
I have found many similar problems, but no one suits mine.
My Product class:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table
public class Product {
#Id
private int id;
private String name;
#Column(name = "description")
private String desc;
private double price;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
Interface ProductRepository:
import HIB_UD_01.product.entities.Product;
import org.springframework.data.repository.CrudRepository;
public interface ProductRepository extends CrudRepository<Product, Integer> {
}
ProductdataApplication:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class ProductdataApplication {
public static void main(String[] args) {
SpringApplication.run(ProductdataApplication.class, args);
}
}
And my Test class:
import HIB_UD_01.product.entities.Product;
import HIB_UD_01.product.repos.ProductRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
#RunWith(SpringRunner.class)
#SpringBootTest
public class ProductdataApplicationTests {
#Autowired
ProductRepository repository;
#Test
public void contextLoads() {
}
#Test
public void testCreate() {
Product product = new Product();
product.setId(1);
product.setName("Iphone");
product.setDesc("Awesome");
product.setPrice(1000d);
repository.save(product);
}
}
And last,my properites file:
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=password
I should put data about product into db, but I get an error:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'HIB_UD_01.product.ProductdataApplicationTests': Unsatisfied dependency expressed through field 'repository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'HIB_UD_01.product.repos.ProductRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
You probably have to enable repositories on your SpringBootApplication class (or in a separate configuration class):
https://www.concretepage.com/spring-boot/spring-boot-crudrepository-example
If that doesn't work, make sure your SpringBootApplication class is a package higher then the rest of your classes, so SpringBoot can autodetect your beans. (And you can try to annotate your repository with #Repository then, to make sure SpringBoot autodetects your repository.)
Also see:
https://dzone.com/articles/the-springbootapplication-annotation-example-in-ja
https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-structuring-your-code.html
OK, problem fixed. I added #Repository to ProductRepository. I cleared repository folder and download new fresh repositories.
Then I have error with time zone in connection to MySQL. So I edit my properities file:
spring.datasource.url=jdbc:mysql://localhost:3306/mydb?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
Thank you for your help!

Java Spring Boot problem LoggiFailureAnalysisReporter

I am new to Boot-Spring apparently, I mostly copy some code from youtube on this case. However, after modification, in the end, I got a message like this;
APPLICATION FAILED TO START
Description:
Field postService in com.example.demo.BlogController required a bean of type 'Server.PostService' that could not be found.
Action:
Consider defining a bean of type 'Server.PostService' in your configuration.
.....Any idea how to deal with this situation. Thank you for the support.
1stclass-BlogApplciation-----com.example.demo(package)
2nd-Blog Controller--------same package as BlogApplication
3rdclass-Post---entities
4rthclass-PostRepositories---Repositories
**package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class BlogApplication {
public static void main(String[] args) {
SpringApplication.run(BlogApplication.class, args);
}
}**
**package com.example.demo;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import Server.PostService;
import entities.Post;
import java.util.Date;
#RestController
public class BlogController {
#Autowired
private PostService postService;
#GetMapping(value="/")
public String index() {
return "index";
}
#GetMapping(value="/posts")
public List<Post>posts(){
return postService.getAllPosts();
}
#PostMapping(value="/post")
public void publishPost(#RequestBody Post post) {
if(post.getDatecreation() == null)
post.setDatecreation(new Date());
postService.insert(post);
}
}**
**package entities;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Post {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String title;
private String body;
private Date Datecreation;
public Post() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String gettitle() {
return title;
}
public void settitle(String title) {
this.title= title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public Date getDatecreation() {
return Datecreation;
}
public void setDatecreation(Date datecreation) {
this.Datecreation = datecreation;
}
}**
**package Repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import entities.Post;
#Repository
public interface PostRepository extends JpaRepository<Post,Long>{
}**
Your BlogApplication Class, which is the class annotated with #SpringBootApplication is in the package com.example.demo. That means that, by default, Spring is going to launch a Component Scan starting from that package.
The problem is that your class PostService and your interface PostRepository are not in the same package as (or in a sub-package of) com.example.demo, so Spring can't find them and won't automatically create these beans for you.
To correct this issue, move the packages you created inside your root package (com.example.demo).
You can find more information about the use of #SpringBootApplication here.
EDIT:
You are missing PostService class or you have imported incorrect class as Server.PostService.
try to create a service like this one:
#Component
public class PostService {
public List<Post> getAllPosts(){
//your code
}
}

Spring boot mongodb auditing error

I'm trying to configure mongodb auditing in my spring boot app, and I having this error when trying to persist my domain class:
java.lang.IllegalArgumentException: Couldn't find PersistentEntity for type class com.example.hateoasapi.domain.Post!
Docs from here https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#auditing says that all this configs enough, but I don't know why it doesn't work in my project. Could someone help me?
My mongodb config class:
package com.example.hateoasapi.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.config.EnableMongoAuditing;
import org.springframework.data.mongodb.core.MongoTemplate;
import com.mongodb.MongoClient;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import java.util.Collection;
import java.util.Collections;
#Configuration
#EnableMongoAuditing
#EnableMongoRepositories(value = "com.example.hateoasapi.repository")
public class MongoConfig extends AbstractMongoConfiguration {
#Value("${spring.data.mongodb.database}")
private String databaseName;
#Value("${spring.data.mongodb.host}")
private String databaseHost;
#Value("${spring.data.mongodb.port}")
private Integer databasePort;
#Override
protected String getDatabaseName() {
return this.databaseName;
}
#Bean
#Override
public MongoClient mongoClient() {
return new MongoClient(databaseHost, databasePort);
}
#Bean
public MongoTemplate mongoTemplate() {
return new MongoTemplate(mongoClient(), databaseName);
}
#Override
protected Collection<String> getMappingBasePackages() {
return Collections.singleton("com.example.hateoasapi.domain");
}
}
AuditorAware implementation:
package com.example.hateoasapi.config;
import com.example.hateoasapi.domain.User;
import org.springframework.data.domain.AuditorAware;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import java.util.Optional;
#Component
public class SecurityAuditor implements AuditorAware<User> {
#Override
public Optional<User> getCurrentAuditor() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null || !authentication.isAuthenticated()) {
return null;
}
return Optional.of((User) authentication.getPrincipal());
}
}
And my domain class:
package com.example.hateoasapi.domain;
import javax.persistence.Id;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import org.joda.time.DateTime;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
import org.springframework.hateoas.ResourceSupport;
import com.fasterxml.jackson.annotation.JsonCreator;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.*;
import java.io.Serializable;
import java.util.List;
import com.example.hateoasapi.controller.*;
#Getter
#Setter
#ToString
#Document
public class Post extends ResourceSupport implements Serializable {
#Id
#Field(value = "_id")
private String objectId;
#DBRef
private List<Comment> comments;
#DBRef
private User author;
#NotBlank
private String body;
#NotBlank
private String title;
private String categoryId;
#NotEmpty(message = "Tags cannot be empty")
private List<PostTag> tags;
#CreatedDate
private DateTime createdDate;
#LastModifiedDate
private DateTime lastModifiedDate;
#CreatedBy
private User createdBy;
private Long views;
private List<PostRating> likes;
private List<PostRating> dislikes;
#JsonCreator
public Post() {}
public Post(String title, String body) {
this.body = body;
this.title = title;
}
public Post(User author, String body, String title, String categoryId, List<PostTag> tags) {
this.author = author;
this.body = body;
this.title = title;
this.categoryId = categoryId;
this.tags = tags;
}
public void addLinks() {
this.add(linkTo(methodOn(PostController.class).getAllPosts(null)).withSelfRel());
}
}
I solved this issue with the next configuration:
#Configuration
#EnableMongoRepositories(basePackages = "YOUR.PACKAGE")
#EnableMongoAuditing
public class MongoConfig extends AbstractMongoConfiguration {
#Value("${spring.data.mongodb.host}")
private String host;
#Value("${spring.data.mongodb.port}")
private Integer port;
#Value("${spring.data.mongodb.database}")
private String database;
#Override
public MongoClient mongoClient() {
return new MongoClient(host, port);
}
#Override
protected String getDatabaseName() {
return database;
}
#Bean
public MongoTemplate mongoTemplate() throws Exception {
return new MongoTemplate(mongoDbFactory(), mappingMongoConverter());
}
#Bean
public MongoDbFactory mongoDbFactory() {
return new SimpleMongoDbFactory(mongoClient(), database);
}
}
just add the bean for MongoTemplate with the constructor of MongoTemplate(MongoDbFactory mongoDbFactory, #Nullable MongoConverter mongoConverter)
Quoting from JIRA ticket
You need to pipe the MappingMongoConverter that's available in the environment into MongoTemplate as well, i.e. use new MongoTemplate(dbFactory, converter). The constructor you use is for convenience, one-off usages. We usually recommend to use AbstractMongoConfiguration in case you'd like to customize anything MongoDB specific as this makes sure the components are wired together correctly.
More specifically, you need to inject pre-configured MappingMongoConverter or if you need to use your own converter, at least use pre-configured MongoMappingContext.
I had this problem also with spring boot 2.2
I had both #EnableMongoRepositories and #EnableMongoAuditing as configuration and i got the error Couldn't find PersistentEntity for type class
the problem in my case was the structure of the packages: Application class was a level lower than part of my model that used auditing.
I found on many forum posts that the 2 annotations are not compatible together in spring 2.2, but after restructuring the packages I was able to use both with success in spring boot 2.2
If you use the last version of Spring boot (2.0) and Spring Data, #EnableMongoAuditing
#EnableMongoRepositories are not compatible. It's the same with EnableReactiveMongoRepositories annotation.
If you want to enable mongo auditing, you need to remove your MongoConfig class, use config file to define your mongodb connection and everything will work.
If you use the last version of Spring boot (2.0) and Spring Data, #EnableMongoAuditing and #EnableMongoRepositories, try remove #EnableMongoRepositories. It should be working just this sample project - https://github.com/hantsy/spring-reactive-sample/tree/master/boot-data-mongo

Categories