Приложение Spring Boot-бин не может быть зарегистрирован - PullRequest
0 голосов
/ 16 марта 2020

Я только что создал новый проект 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;
}

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()
}

Структура проекта:

enter image description here

Но каждый раз, когда я запускаю код, я получаю исключение:

***************************
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.

Хотя у меня есть только один репозиторий в моем проекте

1 Ответ

1 голос
/ 16 марта 2020

Удалить implementation 'org.springframework.boot:spring-boot-starter-data-jpa' из build.gradle

Если вам действительно нужно использовать оба типа репозиториев (jpa и mon go), вы можете поиграть с фильтрами исключения для их сканирования. Что-то вроде:

@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);
    }

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...