Java 考虑在您的配置中定义一个类型的 bean

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48240271/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 02:48:02  来源:igfitidea点击:

Consider defining a bean of type in your configuration

javaspringmongodbspring-boot

提问by Chase

I am following this tutorial ( https://www.youtube.com/watch?v=Hu-cyytqfp8) and trying to connect to MongoDB on a remote server in Spring Boot. I get the following message when I run the application.

我正在关注本教程 ( https://www.youtube.com/watch?v=Hu-cyytqfp8) 并尝试在 Spring Boot 的远程服务器上连接到 MongoDB。我在运行应用程序时收到以下消息。

Description: Parameter 0 of constructor in com.mongotest.demo.Seeder required a bean of type 'com.mongotest.repositories.StudentRepository' that could not be found.

Action: Consider defining a bean of type 'com.mongotest.repositories.StudentRepository' in your configuration.

说明:com.mongotest.demo.Seeder 中构造函数的参数 0 需要一个无法找到的类型为“com.mongotest.repositories.StudentRepository”的 bean。

行动:考虑在你的配置中定义一个“com.mongotest.repositories.StudentRepository”类型的bean。

The project structure.

项目结构。

enter image description here

在此处输入图片说明

And here are my classes

这是我的课程

    @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

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>

采纳答案by Saravana

Please add below annotations in DemoApplication

请在下面添加注释 DemoApplication

@SpringBootApplication
@ComponentScan("com.mongotest") //to scan packages mentioned
@EnableMongoRepositories("com.mongotest") //to activate MongoDB repositories
public class DemoApplication { ... }

回答by Ankit Kumar

If you wish to avoid writing annotations you can simply change your packages com.mongotest.entities to com.mongotest.demo.entities and com.mongotest.repositories to com.mongotest.demo.repositories

如果您希望避免编写注释,您可以简单地将包 com.mongotest.entities 更改为 com.mongotest.demo.entities 并将 com.mongotest.repositories 更改为 com.mongotest.demo.repositories

Spring Boot architecture will take care of rest. Actually other files and packages are supposed to be either at same level or below your DemoApplication.java.

Spring Boot 架构将负责休息。实际上,其他文件和包应该与您的 DemoApplication.java 处于同一级别或以下。

回答by Saurabh

In my case , I was getting same error using mysql db

就我而言,我在使用 mysql db 时遇到了同样的错误

solved using @EnableJpaRepositories

使用@EnableJpaRepositories解决

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

回答by Sushrut Kanetkar

I have 3 helper classes RedisManager, JWTTokenCreator & JWTTokenReader which I needed to pass in constructor as dependency of SessionService spring service.

我有 3 个帮助类 RedisManager、JWTTokenCreator 和 JWTTokenReader,我需要将它们作为 SessionService spring 服务的依赖项传入构造函数。

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

The service class is as follows

服务类如下

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

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

   }
}

回答by rahul tiwari

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

回答by Dheeraj

The problem here is with the annotation you defined.

这里的问题在于您定义的注释。

@ComponentScan("com.mongotest")

@ComponentScan("com.mongotest")

This will scan all the relevant packages under the project structure 'com.mongotest' and initializes the beans in all the subpackage classes.

这将扫描项目结构“com.mongotest”下的所有相关包,并初始化所有子包类中的 bean。