Рассмотрите возможность определения компонента типа в вашей конфигурации

Я следую этому руководству (https://www.youtube.com/watch?v=Hu-cyytqfp8) и пытается подключиться к MongoDB на удаленном сервере в Spring Boot. Когда я запускаю приложение, я получаю следующее сообщение.

Описание: Параметр 0 конструктора в com.mongotest.demo.Seeder требовал bean-объекта типа com.mongotest.repositories.StudentRepository, который не удалось найти.

Действие: Рассмотрите возможность определения bean-компонента типа com.mongotest.repositories.StudentRepository в вашей конфигурации.

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

введите описание изображения здесь

А вот и мои занятия

    @Document(collection = "Students")
    public class Student {

        @Id
        private String number;
        private String name;
        @Indexed(direction = IndexDirection.ASCENDING)
        private int classNo;

    //Constructor and getters and setters.
    }

    ================================

    @Repository
    public interface StudentRepository extends MongoRepository<Student, String>{

    }

    ================================

    @Component
    @ComponentScan({"com.mongotest.repositories"})
    public class Seeder implements CommandLineRunner{

        private StudentRepository studentRepo;

        public Seeder(StudentRepository studentRepo) {
            super();
            this.studentRepo = studentRepo;
        }

        @Override
        public void run(String... args) throws Exception {
            // TODO Auto-generated method stub

            Student s1 = new Student("1","Tom",1);
            Student s2 = new Student("2","Jerry",1);
            Student s3 = new Student("3","Kat",2);
            studentRepo.deleteAll();
            studentRepo.save(Arrays.asList(s1,s2,s3));

        }

    }

    ================================

    @SpringBootApplication
    public class DemoApplication {
        public static void main(String[] args) {
            SpringApplication.run(DemoApplication.class, args);
        }
    }

pom.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>

        <groupId>com.mongotest</groupId>
        <artifactId>demo</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <packaging>jar</packaging>

        <name>demo</name>
        <description>Demo project for Spring Boot</description>

        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>1.5.9.RELEASE</version>
            <relativePath /> <!-- lookup parent from repository -->
        </parent>

        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
            <java.version>1.8</java.version>
        </properties>

        <dependencies>
            <dependency>
                <groupId>org.mongodb</groupId>
                <artifactId>mongo-java-driver</artifactId>
                <version>3.4.2</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-mongodb</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
        </dependencies>

        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>


    </project>

person Chase    schedule 13.01.2018    source источник
comment
см. stackoverflow.com/a/45012168/3344829, можете ли вы попробовать версию весенней загрузки 1.5.1 или меньше   -  person Saravana    schedule 13.01.2018
comment
Я пробовал 1.5.1.RELEASE и 1.5.0.RELEASE ... все еще не работает   -  person Chase    schedule 13.01.2018
comment
нам нужно активировать репозитории mongo с помощью @EnableMongoRepositories, пожалуйста, посмотрите ответ   -  person Saravana    schedule 13.01.2018
comment
Попробуйте аннотировать класс StudentRepository с помощью @Service. Я видел это в другом ответе, и это сработало для меня.   -  person Lycanthropeus    schedule 14.04.2021


Ответы (5)


Добавьте аннотации в DemoApplication ниже

@SpringBootApplication
@ComponentScan("com.mongotest") //to scan packages mentioned
@EnableMongoRepositories("com.mongotest") //to activate MongoDB repositories
public class DemoApplication { ... }
person Saravana    schedule 13.01.2018
comment
Не могли бы вы добавить какие-нибудь пояснения? - person ghosh; 09.05.2021

Если вы не хотите писать аннотации, вы можете просто изменить свои пакеты com.mongotest.entities на com.mongotest.demo.entities и com.mongotest.repositories на com.mongotest.demo.repositories

Об остальном позаботится архитектура Spring Boot. На самом деле другие файлы и пакеты должны быть либо на том же уровне, либо ниже вашего DemoApplication.java.

person Ankit Kumar    schedule 13.01.2018

В моем случае я получал ту же ошибку, используя mysql db

решено с помощью @EnableJpaRepositories

@SpringBootApplication
@ComponentScan("com.example.repositories")//to scan repository files
@EntityScan("com.example.entities")
@EnableJpaRepositories("com.example.repositories")
public class EmployeeApplication implements CommandLineRunner{ ..}
person Saurabh    schedule 11.08.2018

У меня есть 3 вспомогательных класса RedisManager, JWTTokenCreator и JWTTokenReader, которые мне нужно было передать в конструктор как зависимость от службы Spring SessionService.

@SpringBootApplication
@Configuration
public class AuthenticationServiceApplication {
  @Bean
  public SessionService sessionService(RedisManager redisManager, JWTTokenCreator tokenCreator, JWTTokenReader tokenReader) {
    return new SessionService(redisManager,tokenCreator,tokenReader);
  }

  @Bean
  public RedisManager redisManager() {
    return new RedisManager();
  }

  @Bean
  public JWTTokenCreator tokenCreator() {
    return new JWTTokenCreator();
  }

  @Bean
  public JWTTokenReader JWTTokenReader() {
    return new JWTTokenReader();
  }

  public static void main(String[] args) {
     SpringApplication.run(AuthenticationServiceApplication.class, args);
  }
}

Класс обслуживания следующий

@Service
@Component
public class SessionService {
  @Autowired
  public SessionService(RedisManager redisManager, JWTTokenCreator 
      tokenCreator, JWTTokenReader tokenReader) {

      this.redisManager = redisManager;
      this.tokenCreator = tokenCreator;
      this.jwtTokenReader = tokenReader;

   }
}
person Sushrut Kanetkar    schedule 03.01.2019

Проблема здесь в аннотации, которую вы определили.

@ComponentScan ("com.mongotest")

Это просканирует все соответствующие пакеты в структуре проекта com.mongotest и инициализирует bean-компоненты во всех классах подпакетов.

person Dheeraj    schedule 18.04.2020