关于java:\\’字段需要一个无法找到的类型的bean。’使用mongodb的Spring Restful API错误

'Field required a bean of type that could not be found.' error spring restful API using mongodb

所以我在接下来的两周里一直在学习Spring,一直在学习本教程

构建RESTful Web服务

一切都很好,直到我尝试将其集成到mongodb中为止。因此,我按照本教程进行操作。

使用MongoDB访问数据

但是我的练习仍然部分使用第一个。所以我的项目目录结构是这样的。

1
2
3
4
5
6
7
8
9
10
11
12
13
src/
a"?a"€a"€ main/
a"
?   a""a"€a"€ java/
|       a"?a"€a"€ model/
|       |   a"
"a"€a"€ User.java
|       a"
?a"€a"€ rest/
|       |   a"?a"€a"€ Application.java
|       |   a"
?a"€a"€ IndexController.java
|       |   a""a"€a"€ UsersController.java
|       a""a"€a"€ service/
|           a""a"€a"€ UserService.java
a""a"€a"€ resources/
    a""a"€a"€ application.properties

这是我的模型/User.java文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package main.java.model;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection="user")
public class User {

    private int age;
    private String country;
    @Id
    private String id;
    private String name;


    public User() {
        super();
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }
}

这是我的rest / UsersController.java文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package main.java.rest;

import java.util.List;
import main.java.service.UserService;
import main.java.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value ="/users")
public class UsersController {

    @Autowired
    UserService userService;

    @RequestMapping(method = RequestMethod.GET)
    public List<User> getAllUsers() {
        return userService.findAll();
    }
}

这是我的service / UserService.java文件

1
2
3
4
5
6
7
8
9
package main.java.service;

import java.util.List;
import main.java.model.User;
import org.springframework.data.mongodb.repository.MongoRepository;

public interface UserService extends MongoRepository<User, String> {
    public List<User> findAll();
}

我可以编译它们(我正在使用gradle进行编译,因为我正在按照本教程进行操作),但是当我运行jar文件时,它会抛出此错误。

APPLICATION FAILED TO START

Description:

Field userService in main.java.rest.UsersController required a bean of
type 'main.java.service.UserService' that could not be found.

Action:

Consider defining a bean of type 'main.java.service.UserService' in
your configuration.

不确定是什么问题,我开始四处搜索,发现需要包含Beans.xml文件并在其中注册userService。我做到了,但是没用。我真的很陌生,所以我对发生的事情一无所知。


解决了。因此,默认情况下,将扫描所有属于@SpringBootApplication声明的软件包。

假设在com.example.something内部声明了具有@SpringBootApplication声明的主类ExampleApplication,则将扫描所有com.example.something之下的组件,而不会扫描com.example.applicant

因此,基于此问题,有两种方法可以执行此操作。使用

1
2
@SpringBootApplication(scanBasePackages={
"com.example.something","com.example.application"})

这样,应用程序将扫描所有指定的组件,但是我认为如果规模越来越大怎么办?

因此,我使用第二种方法,即重组我的程序包,它起作用了!现在我的包结构变成了这样。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
src/
a"?a"€a"€ main/
a"
?   a""a"€a"€ java/
|       a"?a"€a"€ com.example/
|       |   a"
"a"€a"€ Application.java
|       a"
?a"€a"€ com.example.model/
|       |   a""a"€a"€ User.java
|       a"?a"€a"€ com.example.controller/
|       |   a"
?a"€a"€ IndexController.java
|       |   a""a"€a"€ UsersController.java
|       a""a"€a"€ com.example.service/
|           a""a"€a"€ UserService.java
a""a"€a"€ resources/
    a""a"€a"€ application.properties


在service / UserService.java中添加@Service


我也有同样的错误:

1
2
3
4
5
6
7
8
9
10
11
12
***************************
APPLICATION FAILED TO START
***************************

Description:

Field repository in com.kalsym.next.gen.campaign.controller.CampaignController required a bean of type 'com.kalsym.next.gen.campaign.data.CustomerRepository' that could not be found.


Action:

Consider defining a bean of type 'com.kalsym.next.gen.campaign.data.CustomerRepository' in your configuration.de here

我的包裹的构造方法与接受的答案相同。我通过在主类中添加EnableMongoRepositories批注来解决我的问题,如下所示:

1
2
3
4
5
6
7
8
@SpringBootApplication
@EnableMongoRepositories(basePackageClasses = CustomerRepository.class)
public class CampaignAPI {

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

如果需要添加多个,请不要忘记大括号:

1
2
3
4
@EnableMongoRepositories(basePackageClasses
    = {
        MSASMSRepository.class, APartyMappingRepository.class
    })

我遇到了同样的问题,我所要做的就是将应用程序放在比服务,dao和域包高一层的包中。


由于自动导入而花费了很多时间。
为什么从import org.jvnet.hk2.annotations.Service;而不是import org.springframework.stereotype.Service;导入@Service的Intellij Idea!


您必须在服务的实现中添加@Service批注。


该线程现在很旧,但是我正在发布我的答案,这可能对其他人有用。

我有同样的问题。
原来,在其他模块中还有另一个具有相同名称的类。我重命名了该类,它解决了问题。


通常我们可以从两个方面解决这个问题:

  • Spring Boot扫描bean应该使用适当的注释,例如@Component
  • 扫描路径将包括上述所有其他类。
  • 顺便说一下,对于@ Component,@ Repository,@ Service和@Controller之间的区别有很好的解释。


    为了弹跳创建bean并注入它,类应在您的上下文中用@ Componet,@ service,@ Repository等标记。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    package main.java.service;

    import java.util.List;
    import main.java.model.User;
    import org.springframework.data.mongodb.repository.MongoRepository;
    @Repository
    public interface UserService extends MongoRepository<User, String> {
        public List<User> findAll();
    }

    在您的班级中添加@Repository

    示例:

    1
    2
    3
    @Repository
    public class DaoClassName implements IIntefaceDao {
    }

    在控制器类中添加@Component。可能这项工作


    使用所有@注释解决了我的问题。 (是的,我是Spring的新手)
    如果您使用的是服务类,请添加@Service,并为@Controller和@Repository添加相同的内容。

    然后在App.java上使用此批注解决了该问题(我正在使用JPA Hibernate)。

    1
    2
    3
    4
    5
    @SpringBootApplication
    @EnableAutoConfiguration(exclude = { ErrorMvcAutoConfiguration.class })
    @ComponentScan(basePackages = {"es.unileon.inso2"})
    @EntityScan("es.unileon.inso2.model")
    @EnableJpaRepositories("es.unileon.inso2.repository")

    打包树:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    src/
    a"?a"€a"€ main/
    a"
    ?   a""a"€a"€ java/
    |       a"?a"€a"€ es.unileon.inso2/
    |       |   a"
    "a"€a"€ App.java
    |       a"
    ?a"€a"€ es.unileon.inso2.model/
    |       |   a""a"€a"€ User.java
    |       a"?a"€a"€ es.unileon.inso2.controller/
    |       |   a"
    ?a"€a"€ IndexController.java
    |       |   a""a"€a"€ UserController.java
    |       a"?a"€a"€ es.unileon.inso2.service/
    |       |    a"
    "a"€a"€ UserService.java
    |       a"
    "a"€a"€ es.unileon.inso2.repository/
    |            a"
    "a"€a"€ UserRepository.java
    a"
    "a"€a"€ resources/
        a"
    "a"€a"€ application.properties

    我遇到了同样的问题,我从控制器中删除了@Autowired注释。如果您的存储库是一个类,则需要使用Autowired Annotation来使用存储库,但是当它是一个接口时,根据我的经验,您无需添加@Autowired Annotation。


    我有相同的问题,通过添加来解决
    @EnableMongoRepositories(" in.topthree.util")

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    package in.topthree.core;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

    import in.topthree.util.Student;

    @SpringBootApplication
    @EnableMongoRepositories("in.topthree.util")
    public class Run implements CommandLineRunner {

        public static void main(String[] args) {
            SpringApplication.run(Run.class, args);
            System.out.println("Run");
        }

        @Autowired
        private Process pr;

        @Override
        public void run(String... args) throws Exception {
            pr.saveDB(new Student("Testing","FB"));
            System.exit(0);
        }

    }

    我的存储库是:

    1
    2
    3
    4
    5
    6
    7
    8
    package in.topthree.util;

    import org.springframework.data.mongodb.repository.MongoRepository;

    public interface StudentMongo extends MongoRepository<Student, Integer> {

        public Student findByUrl(String url);
    }

    现在可以正常工作了


    我有同样的问题。我的错误是我在服务接口上使用了@Service批注。
    @Service批注应应用于ServiceImpl类。


    我来到这篇文章时是在将Spring Webflux与Mongo Repository结合使用时寻求帮助。

    我的错误类似于所有者

    1
    2
    Field usersRepository in foobar.UsersService required
    a bean of type 'foobar.UsersRepository' that could not be found.

    在使用Spring MVC之前,我对这个错误感到惊讶。

    因为找不到帮助很明显,所以我正在回答这个问题,因为它以某种方式相关并且这个问题在搜索结果中很高。

    第一件事是您必须记住答案中提到的标记为已接受的内容-程序包层次结构。

    第二件重要的事情是,如果您使用Webflux,则在使用Spring MVC时需要使用一些其他软件包,例如对于MongoDB,您需要添加

    1
    2
    3
    4
    <dependency>
        <groupId>org.springframework.boot</groupId>
        spring-boot-starter-data-mongodb-reactive</artifactId>
    </dependency>

    以-reactive结尾。


    在dao类中添加@Repository

    1
    2
    3
    4
    5
        @Repository
        public interface UserDao extends CrudRepository<User, Long> {
             User findByUsername(String username);
             User findByEmail(String email);    
          }


    您必须导入spring-boot-starter-data-jpa
    如果您使用spring boot

    ,则视情况而定


    对于通过谷歌搜索通用bean错误消息而带到这里但实际上试图通过客户端界面上的@FeignClient注释向其Spring Boot应用程序添加伪客户端的任何人,上述解决方案均不起作用为你。

    要解决此问题,需要将@EnableFeignClients批注添加到Application类,如下所示:

    1
    2
    3
    4
    @SpringBootApplication
    // ... (other pre-existing annotations) ...
    @EnableFeignClients // <------- THE IMPORTANT ONE
    public class Application {

    这样,此修复程序类似于上述的@EnableMongoRepositories修复程序。可惜的是,这种通用错误消息需要针对每种情况进行如此量身定制的修复...


    我在目标文件夹中的Mapper实现类已被删除,因此我的Mapper接口不再具有任何实现类。因此我得到了相同的错误Field *** required a bean of type ***Mapper that could not be found.

    我只需要用maven重新生成我的映射器实现,然后刷新项目...


    在我的情况下,我只是将MyprojectApplication类放入具有相同级别的模型,控制器,服务包的包(com.example.start)中。


    当两个bean具有相同的名称时,可能会发生这种情况。

    Module1Beans.java ???

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    @Configuration
    public class Module1Beans {
        @Bean
        public GoogleAPI retrofitService(){
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl("https://www.google.com/")
                    .addConverterFactory(JacksonConverterFactory.create())
                    .build();
            return retrofit.create(GoogleAPI.class);
        }
    }

    Module2Beans.java ???

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    @Configuration
    public class Module2Beans {
        @Bean
        public GithubAPI retrofitService(){
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl("https://www.github.com/")
                    .addConverterFactory(JacksonConverterFactory.create())
                    .build();
            return retrofit.create(GithubAPI.class);
        }
    }

    首先创建一个名为retrofitService的bean,其类型为GoogleAPI,然后由GithubAPI覆盖,因为它们都由retrofitService()方法创建。
    现在,当您@AutowiredGoogleAPI时,您会收到类似Field googleAPI in com.example.GoogleService required a bean of type 'com.example.rest.GoogleAPI' that could not be found.

    的消息


    两种类型的mongo依赖项-

    1
    2
    3
    4
    5
    6
    7
    8
    <dependency>
        <groupId>org.springframework.boot</groupId>
        spring-boot-starter-data-mongodb-reactive</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        spring-boot-starter-data-mongodb</artifactId>
    </dependency>

    两种类型的存储库-

    1
    2
    MongoRepository
    ReactiveMongoRepository

    确保使用正确的组合。


    我知道它很旧,但想加5美分。

    我在文件夹结构中使用了.service.service.impl来将服务与其实现分开。忘记实现ServiceImplementation部分。


    对我来说,此消息:

    1
    org.apache.wicket.WicketRuntimeException: Can't instantiate page using constructor 'public org.package.MyClass(org.apache.wicket.request.mapper.parameter.PageParameters)' and argument ''. Might be it doesn't exist, may be it is not visible (public).

    意味深长的"在我的小门单元测试中,您必须像这样手动添加该豆"

    1
    appContext.putBean(myClass);

    我按照这里的OP的所有步骤和说明进行操作,照顾了用户名和密码周围的空格(即使spring照顾了属性文件中的空格),仍然面对

    1
    could not find bean for ___Repository

    (扩展JPARepository的接口)

    或在添加@EnableJPARepository

    之后

    1
    could not find bean for EntityManagerFactory

    我通过将pom.xml中的Spring Boot Starter父版本从2.3.2更改为2.2.1来解决了该问题

    1
    2
    3
    4
    5
    6
    <parent>
        <groupId>org.springframework.boot</groupId>
        spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    并添加以下依赖项

    1
    2
    3
    4
    5
    <dependency>
        <groupId>mysql</groupId>
        mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>

    我不需要添加以下任何内容,Spring Boot会自己添加

  • @EnableJPAReposity-因为我已经用相同的根包安装了所有类
  • 在application.properties中启用了spring.data.jpa.repositories。
  • 应用程序属性中的spring.datasource.driverClassName = com.mysql.jdbc.Driver

  • 使用此方法解决了我的问题。

    1
    @SpringBootApplication(scanBasePackages={"com.example.something","com.example.application"})