在idea中使用gradle創建了一個mongodb的demo,在啟動程序中報錯提示MongoTemplate注入失敗。這個問題怎么解決?
1.build.gradle如下
plugins {
id 'org.springframework.boot' version '2.2.6.RELEASE'
id 'io.spring.dependency-management' version '1.0.9.RELEASE'
id 'java'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
configurations {
developmentOnly
runtimeClasspath {
extendsFrom developmentOnly
}
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
testImplementation 'org.springframework.security:spring-security-test'
}
test {
useJUnitPlatform()
}
2.出錯位置
package com.example.demo.controller;
import com.example.demo.model.request.User;
import com.example.demo.model.response.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@Autowired
private MongoTemplate mongoTemplate;
@PostMapping("/createUser")
public Result createUser(@RequestBody User user) throws Exception {
mongoTemplate.save(user);
Result result = new Result("success");
return result;
}
}
3.報錯如下
escription:
Field mongoTemplate in com.example.demo.controller.UserController required a bean of type 'org.springframework.data.mongodb.core.MongoTemplate' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
The following candidates were found but could not be injected:
- Bean method 'mongoTemplate' in 'MongoDbFactoryDependentConfiguration' not loaded because @ConditionalOnBean (types: org.springframework.data.mongodb.MongoDbFactory; SearchStrategy: all) did not find any beans of type org.springframework.data.mongodb.MongoDbFactory
Action:
Consider revisiting the entries above or defining a bean of type 'org.springframework.data.mongodb.core.MongoTemplate' in your configuration.
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/18324.html
標籤:MongoDB
