IT TIP

구성 [Spring-Boot]에서 '패키지'유형의 빈 정의를 고려하십시오.

itqueen 2020. 10. 27. 23:56
반응형

구성 [Spring-Boot]에서 '패키지'유형의 빈 정의를 고려하십시오.


다음과 같은 오류가 발생합니다.

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of method setApplicant in webService.controller.RequestController required a bean of type 'com.service.applicant.Applicant' that could not be found.


Action:

Consider defining a bean of type 'com.service.applicant.Applicant' in your configuration.

이 오류는 전에 본 적이 없지만 @Autowire가 작동하지 않는 것이 이상합니다. 프로젝트 구조는 다음과 같습니다.

지원자 인터페이스

public interface Applicant {

    TApplicant findBySSN(String ssn) throws ServletException;

    void deleteByssn(String ssn) throws ServletException;

    void createApplicant(TApplicant tApplicant) throws ServletException;

    void updateApplicant(TApplicant tApplicant) throws ServletException;

    List<TApplicant> getAllApplicants() throws ServletException;
}

신청자 Impl

@Service
@Transactional
public class ApplicantImpl implements Applicant {

private static Log log = LogFactory.getLog(ApplicantImpl.class);

    private TApplicantRepository applicantRepo;

@Override
    public List<TApplicant> getAllApplicants() throws ServletException {

        List<TApplicant> applicantList = applicantRepo.findAll();

        return applicantList;
    }
}

이제 Autowire Applicant 만 가능하고 액세스 할 수 있어야합니다.하지만이 경우에는 제 전화를 걸어도 작동하지 않습니다. @RestController:

@RestController
public class RequestController extends LoggingAware {

    private Applicant applicant;

    @Autowired
    public void setApplicant(Applicant applicant){
        this.applicant = applicant;
    }

    @RequestMapping(value="/", method = RequestMethod.GET)
    public String helloWorld() {

        try {
            List<TApplicant> applicantList = applicant.getAllApplicants();

            for (TApplicant tApplicant : applicantList){
                System.out.println("Name: "+tApplicant.getIndivName()+" SSN "+tApplicant.getIndSsn());
            }

            return "home";
        }
        catch (ServletException e) {
            e.printStackTrace();
        }

        return "error";
    }

}

------------------------ 업데이트 1 -----------------------

나는 추가했다

@SpringBootApplication
@ComponentScan("module-service")
public class WebServiceApplication extends SpringBootServletInitializer {

    @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(WebServiceApplication.class);
    }

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

}

오류가 사라졌지 만 아무 일도 일어나지 않았습니다. 그러나 추가하기 전에 Applicant에서 다루는 모든 것을 주석으로 처리했을 때 문자열을 반환 할 수 있었 으므로 작업 중임 을 의미하므로 이제 건너 뛰고 있습니다. 나는 지금 못 생겼다 .RestController@ComponentScan()UIRestControllerWhitelabel Error Page

--------------------- 업데이트 2 --------------------------- ---

불평하는 빈의 기본 패키지를 추가했습니다. 오류는 다음과 같습니다.

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of method setApplicantRepo in com.service.applicant.ApplicantImpl required a bean of type 'com.delivery.service.request.repository.TApplicantRepository' that could not be found.


Action:

Consider defining a bean of type 'com.delivery.request.request.repository.TApplicantRepository' in your configuration.

나는 추가했다 @ComponentScan

@SpringBootApplication
@ComponentScan({"com.delivery.service","com.delivery.request"})
public class WebServiceApplication extends SpringBootServletInitializer {

    @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(WebServiceApplication.class);
    }

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

}

---------------------------- 업데이트 3 -------------------- -

첨가:

@SpringBootApplication
@ComponentScan("com")
public class WebServiceApplication extends SpringBootServletInitializer {

여전히 내에 대해 불평 ApplicantImpl클래스 @Autowires내의 repo TApplicantRepository그것으로.


프로젝트가 여러 모듈로 나뉘었기 때문일 수 있습니다.

@SpringBootApplication
@ComponentScan({"com.delivery.request"})
@EntityScan("com.delivery.domain")
@EnableJpaRepositories("com.delivery.repository")
public class WebServiceApplication extends SpringBootServletInitializer {

지원자 클래스가 스캔되지 않은 것 같습니다. 기본적으로 루트를 넣은 클래스로 시작하는 모든 패키지 @SpringBootApplication가 스캔됩니다.

main클래스 "WebServiceApplication"이 ""에 있다고 가정하면 " com.service.something"에 속하는 모든 구성 요소 com.service.something가 스캔 되고 " "은 스캔 com.service.applicant되지 않습니다.

"WebServiceApplication"이 루트 패키지에 속하고 다른 모든 구성 요소가 해당 루트 패키지의 일부가되도록 패키지를 재구성 할 수 있습니다. 또는 @SpringBootApplication(scanBasePackages={"com.service.something","com.service.application"})"모든"구성 요소가 스프링 컨테이너에서 스캔되고 초기화되도록 등을 포함 할 수 있습니다 .

댓글에 따라 업데이트

maven / gradle에서 관리하는 여러 모듈이있는 경우 모든 봄 요구 사항은 스캔 할 패키지입니다. 스프링에게 "com.module1"을 스캔하라고 지시하고 루트 패키지 이름이 "com.module2"인 다른 모듈이 있으면 해당 구성 요소는 스캔되지 않습니다. Spring에 "com" 을 스캔하도록 지시 하면 " com.module1."및 " com.module2."의 모든 구성 요소를 스캔합니다.


There is a chance...
You might be missing @Service, @Repository annotation on your respective implementation classes.


Basically this happens when you have your Class Application in "another package". For example:

com.server
 - Applicacion.class (<--this class have @ComponentScan)
com.server.config
 - MongoConfig.class 
com.server.repository
 - UserRepository

I solve the problem with this in the Application.class

@SpringBootApplication
@ComponentScan ({"com.server", "com.server.config"})
@EnableMongoRepositories ("com.server.repository") // this fix the problem

Another less elegant way is to: put all the configuration classes in the same package.


In my case I had a terrible mistake. I put @Service up to the service interface.

To fix it, I put @Service on the implementation of service file and it worked for me.


I think you can make it simplified by annotated your repository with @Repository, then it will be enabled automatically by Spring Framework.


This can also happen if you are using Lombok and you add the @RequiredArgsConstructor and @NonNull for fields but some of your fields are not to be injected in the constructor. This is only one of the possibilities to get the the same error.

parameter 0 required a bean of type MissingBeanName that could not be found

In my case the error told me what Controller the problem was in, after removing @NonNull the application started fine


If a bean is in the same package in which it is @Autowired, then it will never cause such an issue. However, beans are not accessible from different packages by default. To fix this issue follow these steps :

  1. Import following in your main class:
    import org.springframework.context.annotation.ComponentScan;
  2. add annotation over your main class :
@ComponentScan(basePackages = {"your.company.domain.package"})
public class SpringExampleApplication {

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

I sought online for an answer but it seems there is no one proper solution to my case: At the very beginning, everything works well as follows:

@Slf4j
@Service
@AllArgsConstructor(onConstructor = @__(@Autowired))
public class GroupService {
    private Repository repository;
    private Service service;
}

Then I am trying to add a map to cache something and it becomes this:

@Slf4j
@Service
@AllArgsConstructor(onConstructor = @__(@Autowired))
public class GroupService {
    private Repository repository;
    private Service service;
    Map<String, String> testMap;
}

Boom!

Description:

Parameter 4 of constructor in *.GroupService required a bean of type 'java.lang.String' that could not be found.


Action:

Consider defining a bean of type 'java.lang.String' in your configuration.

I removed the @AllArgsConstructor(onConstructor = @__(@Autowired)) and add @Autowired for each repository and service except the Map<String, String>. It just works as before.

@Slf4j
@Service
public class SecurityGroupService {
    @Autowired
    private Repository repository;
    @Autowired
    private Service service;
    Map<String, String> testMap;
}

Hope this might be helpful.


In my case these two options worked.

  1. in //@ComponentScan ({"myapp", "myapp.resources","myapp.services"}) include also the package which holds the Application.class in the list, or

  2. Simply add @EnableAutoConfiguration; it automatically recognizes all the spring beans.


@SpringBootApplication
@MapperScan("com.developer.project.mapper")

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

This can happen if the @Service class is marked abstract.


It worked for me after adding below annotation in application:

@ComponentScan({"com.seic.deliveryautomation.mapper"})

I was getting the below error:

"parameter 1 of constructor in required a bean of type mapper that could not be found:


In my case this error appear because my import was wrong, for example, using spring, the import automatically appear:

import org.jvnet.hk2.annotations.Service;

but i needed:

import org.springframework.stereotype.Service;

I had a case where i need to inject RestTemplate into a service class. However, the RestTemplate cannot be picked up by the service class. What I did is to create a wrapper class under the same package as main application and mark the wrapper as Component and autowire this component in the service class. Problem solved. hope it also works for you


If your class dependency is managing by Spring then this issue may occur if we forgot to add default/empty arg constructor inside our POJO class.

참고URL : https://stackoverflow.com/questions/40384056/consider-defining-a-bean-of-type-package-in-your-configuration-spring-boot

반응형