Java 考虑在您的配置中定义一个“包”类型的 bean [Spring-Boot]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40384056/
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-11 22:39:51  来源:igfitidea点击:

Consider defining a bean of type 'package' in your configuration [Spring-Boot]

javaspring-boot

提问by Mike3355

I am getting the following error:

我收到以下错误:

***************************
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.

I have never seen this error before but it's odd that the @Autowire is not working. Here is the project structure:

我以前从未见过此错误,但奇怪的是 @Autowire 不起作用。这是项目结构:

Applicant Interface

申请人界面

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

ApplicantImpl

申请人

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

Now I should be able to just Autowire Applicant and be able to access, however in this case it is not working when I call it in my @RestController:

现在我应该能够只自动装配申请人并能够访问,但是在这种情况下,当我在我的 @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";
    }

}

------------------------UPDATE 1-----------------------

--------------更新 1--------------

I added

我加了

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

}

and the error went away but nothing happened. However when I commented out everything dealing with Applicantin the RestControllerprior to adding @ComponentScan()I was able to return a string the UI, thus meaning my RestControllerwas working, now it is being skipped. I ugly Whitelabel Error Pagenow.

错误消失了,但什么也没发生。但是,当我ApplicantRestController添加之前注释掉所有处理的内容时,@ComponentScan()我能够返回一个字符串 the UI,这意味着我RestController正在工作,现在它被跳过了。我Whitelabel Error Page现在很丑。

---------------------UPDATE 2------------------------------

---------------------更新2--------------------------- ---

I added the base package of the bean it was complaining about. Error reads:

我添加了它抱怨的 bean 的基本包。错误内容:

***************************
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.

I added @ComponentScan

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

}

----------------------------Update 3----------------------

----------------------------更新3------------ ——

adding:

添加:

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

still is complaining about my ApplicantImplclass which @Autowiresmy repo TApplicantRepositoryinto it.

仍然在抱怨我的ApplicantImpl课程,@Autowires我的回购TApplicantRepository进入了它。

采纳答案by Mike3355

It might be because the project has been broken down into different modules.

可能是因为项目已分解为不同的模块。

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

回答by Ameen.M

Your Applicant class is not scanned it seems. By default all packages starting with the root as the class where you have put @SpringBootApplicationwill be scanned.

您的申请人课程似乎没有被扫描。默认情况下,所有以根为您放置的类的包都@SpringBootApplication将被扫描。

suppose your mainclass "WebServiceApplication" is in "com.service.something", then all components that fall under "com.service.something" is scanned, and "com.service.applicant" will not be scanned.

假设您的main类“WebServiceApplication”在“ com.service.something”中,那么所有属于“ com.service.something”的组件都会被扫描,而“ com.service.applicant”将不会被扫描。

You can either restructure your packages such that "WebServiceApplication" falls under a root package and all other components becomes part of that root package. Or you can include @SpringBootApplication(scanBasePackages={"com.service.something","com.service.application"})etc such that "ALL" components are scanned and initialized in the spring container.

您可以重组您的包,使“WebServiceApplication”属于根包,而所有其他组件成为该根包的一部分。或者您可以包含@SpringBootApplication(scanBasePackages={"com.service.something","com.service.application"})etc 以便在 spring 容器中扫描和初始化“所有”组件。

Update based on comment

根据评论更新

If you have multiple modules that are being managed by maven/gradle, all spring needs is the package to scan. You tell spring to scan "com.module1" and you have another module which has its root package name as "com.module2", those components wont be scanned. You can even tell spring to scan "com"which will then scan all components in "com.module1." and "com.module2."

如果您有多个由 maven/gradle 管理的模块,则 Spring 需要的只是要扫描的包。您告诉 spring 扫描“com.module1”并且您有另一个模块,其根包名称为“com.module2”,这些组件将不会被扫描。您甚至可以告诉 spring 扫描“com”,然后它会扫描“ com.module1.”和“ com.module2.”中的所有组件

回答by Dawid Gorczyca

This can also happen if you are using Lombok and you add the @RequiredArgsConstructorand @NonNullfor 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.

如果您使用 Lombok 并添加@RequiredArgsConstructor@NonNullfor 字段,但您的某些字段不会注入到构造函数中,也会发生这种情况。这只是获得相同错误的可能性之一。

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

参数 0 需要一个无法找到的 MissingBeanName 类型的 bean

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

在我的情况下,错误告诉我问题出在哪个控制器上,删除@NonNull应用程序后开始正常

回答by Carlos Marcano

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

我在 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.

另一种不太优雅的方法是:将所有配置类放在同一个包中。

回答by developer07

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

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

回答by Tushar Saha Chowdhury

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

我认为您可以通过使用@Repository 注释您的存储库来简化它,然后Spring Framework 会自动启用它。

回答by CodeWorld

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

有机会...
您可能会丢失@Service,@Repository对各自实现类的注释。

回答by Hearen

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 @Autowiredfor each repositoryand serviceexcept the Map<String, String>. It just works as before.

我删除了@AllArgsConstructor(onConstructor = @__(@Autowired))和添加@Autowired每个repositoryservice除了Map<String, String>. 它就像以前一样工作。

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

Hope this might be helpful.

希望这可能会有所帮助。

回答by Ariel

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

如果@Service 类被标记为抽象,就会发生这种情况。

回答by Sriharsha g.r.v

In my case these two options worked.

在我的情况下,这两个选项有效。

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

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

  1. //@ComponentScan ({"myapp", "myapp.resources","myapp.services"})包括保持该包Application.class在列表中,或者

  2. 只需添加@EnableAutoConfiguration; 它会自动识别所有的 spring bean。