我刚刚创建了一个新的Spring-boot-starter项目,并且正在尝试使用MongoRepository(提及,因为我认为这可能与我的问题有关),并且我只有4个要运行的类,例如:
User.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;
}
UserController.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);
}
}
UserRepository.java
@Repository
public interface UserRepository extends MongoRepository<User, Long> {
}
启动类:
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
build.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.
虽然我的项目中只有一个存储库
问题来源:Stack Overflow
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'从中删除build.gradle
如果确实需要使用两种类型的存储库(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);
}
}
回答来源:Stack Overflow
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。