programing

'필드를 찾을 수없는 유형의 빈이 필요합니다.'

nasanasas 2020. 11. 19. 21:37
반응형

'필드를 찾을 수없는 유형의 빈이 필요합니다.' mongodb를 사용하는 오류 스프링 편안한 API


그래서 저는 몇 주 동안 Spring을 배우고 있었고,이 튜토리얼을 따랐습니다.

RESTful 웹 서비스 구축

mongodb에 통합하려고 할 때까지 모든 것이 잘되었습니다. 그래서 저는이 튜토리얼을 따릅니다.

MongoDB로 데이터 액세스

그러나 내 연습은 부분적으로 여전히 첫 번째 것을 사용하고 있습니다. 그래서 내 프로젝트 디렉토리 구조는 다음과 같습니다.

src/
├── main/
│   └── java/
|       ├── model/
|       |   └── User.java
|       ├── rest/
|       |   ├── Application.java
|       |   ├── IndexController.java
|       |   └── UsersController.java
|       └── service/
|           └── UserService.java
└── resources/
    └── application.properties

이것은 내 모델 /User.java 파일입니다.

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 파일입니다.

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 파일입니다.

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 파일을 실행할 때이 오류가 발생했습니다.


애플리케이션을 시작하지 못했습니다.


기술:

main.java.rest.UsersController의 필드 userService에는 찾을 수없는 'main.java.service.UserService'유형의 Bean이 필요합니다.

동작:

구성에서 'main.java.service.UserService'유형의 Bean을 정의하는 것을 고려하십시오.

무엇이 잘못되었는지 확실하지 않고 인터넷 검색을 시작하고 Beans.xml파일 을 포함 하고 그 안에 userService를 등록 해야한다는 것을 알았 습니다. 내가했지만 작동하지 않습니다. 나는 이것에 정말 익숙해 져서 무슨 일이 일어나고 있는지 전혀 모른다.


해결했습니다. 따라서 기본적으로 @SpringBootApplication선언에 해당하는 모든 패키지가 스캔됩니다.

선언이있는 기본 클래스 ExampleApplication@SpringBootApplication내부 com.example.something선언되어 있다고 가정하면 해당하는 모든 구성 요소 com.example.something는 스캔되지만 스캔 com.example.applicant되지 않습니다.

그래서,이 질문을 바탕으로 두 가지 방법이 있습니다. 사용하다

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

그런 식으로 응용 프로그램은 지정된 모든 구성 요소를 스캔하지만 규모가 커지면 어떻게 될까요?

그래서 두 번째 접근 방식을 사용하여 패키지를 재구성하고 작동했습니다! 이제 내 패키지 구조가 이렇게되었습니다.

src/
├── main/
│   └── java/
|       ├── com.example/
|       |   └── Application.java
|       ├── com.example.model/
|       |   └── User.java
|       ├── com.example.controller/
|       |   ├── IndexController.java
|       |   └── UsersController.java
|       └── com.example.service/
|           └── UserService.java
└── resources/
    └── application.properties

@Serviceservice / UserService.java에를 추가하십시오 .


나는 또한 같은 오류가 있었다.

***************************
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 주석을 추가하여 문제를 해결했습니다.

@SpringBootApplication
@EnableMongoRepositories(basePackageClasses = CustomerRepository.class)
public class CampaignAPI {

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

동일한 문제가 발생하여 서비스, dao 및 도메인 패키지보다 한 수준 높은 패키지에 애플리케이션을 배치하기 만하면되었습니다.


이 스레드는 현재 오래되었지만 다른 사람들에게 유용 할 수있는 내 답변을 게시하고 있습니다.

나는 같은 문제가 있었다. 다른 모듈에 같은 이름을 가진 다른 클래스가 있음이 밝혀졌습니다. 나는 그 수업의 이름을 바꾸고 문제를 해결했습니다.


자동 가져 오기 때문에 많은 시간을 보냈습니다. 인 IntelliJ 아이디어는 somewhy 수입 @Service에서 import org.jvnet.hk2.annotations.Service;대신 import org.springframework.stereotype.Service;!


일반적으로이 문제는 두 가지 측면에서 해결할 수 있습니다.

  1. 적절한 주석을 사용해야 봄 부팅 스캔 콩을 같이 @Component;
  2. 스캔 경로는 다른 모든 위에서 언급 한 것처럼 클래스를 포함합니다.

그건 그렇고, @Component, @Repository, @Service 및 @Controller 의 차이점에 대한 매우 좋은 설명이 있습니다.


컨트롤러 클래스에 @Component를 추가하십시오. 이 일을


내 대상 폴더의 내 Mapper 구현 클래스가 삭제되었으므로 내 Mapper 인터페이스에는 더 이상 구현 클래스가 없습니다. 따라서 동일한 오류가 발생했습니다.Field *** required a bean of type ***Mapper that could not be found.

maven을 사용하여 매퍼 구현을 재생성하고 프로젝트를 새로 고치기 만하면됩니다.


모든 @ 주석을 사용하여 문제를 해결했습니다. (예, 저는 Spring을 처음 사용합니다) 서비스 클래스를 사용하는 경우 @Service를 추가하고 @Controller 및 @Repository에 대해 동일합니다.

그런 다음 App.java의이 주석이 문제를 해결했습니다 (JPA + Hibernate를 사용하고 있습니다).

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

패키지 트리 :

src/
├── main/
│   └── java/
|       ├── es.unileon.inso2/
|       |   └── App.java
|       ├── es.unileon.inso2.model/
|       |   └── User.java
|       ├── es.unileon.inso2.controller/
|       |   ├── IndexController.java
|       |   └── UserController.java
|       ├── es.unileon.inso2.service/
|       |    └── UserService.java
|       └── es.unileon.inso2.repository/
|            └── UserRepository.java
└── resources/
    └── application.properties

@Service서비스 구현에 주석 을 추가 해야합니다.


제 경우에는 Class MyprojectApplication을 동일한 수준의 모델, 컨트롤러, 서비스 패키지로 패키지 (com.example.start)에 넣었습니다.


제 경우에는 abstract복사 및 붙여 넣기를 수행하는 동안 실수로 서비스 클래스 정의했습니다 .

@Serivce
@Valdiated
public abstract class MyService { // remove the abstract modifier!!!
}

I have come to this post looking for help while using Spring Webflux with Mongo Repository.

My error was similar to owner

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

As I was working before with Spring MVC I was surprised by this error.

Because finding help was not so obvious I'm putting answer to this question as it is somehow related and this question is high in search results.

First thing is you must remember about what was mentioned in answer marked as accepted - package hierarchy.

Second important thing is that if you use Webflux you need to use some different package while when using Spring MVC e.g. for MongoDB you need to add

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

with -reactive at the end.


I have same Issue, fixed by Adding @EnableMongoRepositories("in.topthree.util")

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

}

And my Repository is:

package in.topthree.util;

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

public interface StudentMongo extends MongoRepository<Student, Integer> {

    public Student findByUrl(String url);
}

Now Its Working


This may happen when two beans have same names.

Module1Beans.java

@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

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

A bean named retrofitService is first created, and it's type is GoogleAPI, then covered by a GithubAPI becauce they're both created by a retrofitService() method. Now when you @Autowired a GoogleAPI you'll get a message like Field googleAPI in com.example.GoogleService required a bean of type 'com.example.rest.GoogleAPI' that could not be found.


Using this solved my issue.

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

참고URL : https://stackoverflow.com/questions/42907553/field-required-a-bean-of-type-that-could-not-be-found-error-spring-restful-ap

반응형