[英]Spring Boot application-The bean could not be registered
我刚刚创建了一个新的 Spring-boot-starter 项目,我正在尝试使用MongoRepository
(提及是因为我觉得这可能与我的问题有关)并且我只有 4 个我正在尝试运行的类,例如:
用户.java
@Entity
public class User {
@Column(name = "id")
@Id
private Long id;
@Column(name = "name")
private String name;
@Column(name = "email")
private String email;
@Column(name = "password")
private String password;
}
用户控制器.java
@RestController
public class UserController {
@Autowired
private UserRepository userRepository;
@PostMapping("/AddUser")
private ResponseEntity<?> getDistance(@RequestBody User user) throws Exception {
userRepository.save(user);
return ResponseEntity.ok(user);
}
}
用户存储库.java
@Repository
public interface UserRepository extends MongoRepository<User, Long> {
}
主类
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
构建.gradle
plugins {
id 'org.springframework.boot' version '2.2.5.RELEASE'
id 'io.spring.dependency-management' version '1.0.9.RELEASE'
id 'java'
}
group = 'com.javademos'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-mongodb', version: '2.2.5.RELEASE'
implementation 'com.google.maps:google-maps-services:0.1.7'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
}
test {
useJUnitPlatform()
}
项目结构:
但是每次我运行代码时,我都会收到一个异常说:
***************************
APPLICATION FAILED TO START
***************************
Description:
The bean 'userRepository' could not be registered. A bean with that name has already been defined and overriding is disabled.
Action:
Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true
Process finished with exit code 1
我已经仔细检查过,我没有使用任何注释两次,尤其是@Repository。
我已经看到了这个问题,但它仍然无法正常工作。
我只是想知道它为什么这么说
The bean 'userRepository' could not be registered. A bean with that name has already been defined and overriding is disabled.
虽然我的项目中只有一个存储库
从build.gradle
删除implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
如果您确实需要使用两种类型的存储库(jpa 和 mongo),您可以使用排除过滤器进行扫描。 喜欢:
@EnableMongoRepositories(basePackageClasses = UserRepository.class)
@EnableJpaRepositories(excludeFilters =
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = UserRepository.class))
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.