【问题标题】:Consider defining a bean of type 'package' in your configuration [Spring-Boot]考虑在你的配置中定义一个“包”类型的 bean [Spring-Boot]
【发布时间】:2017-03-16 00:11:33
【问题描述】:

我收到以下错误:

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

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

现在我应该能够只使用 Autowire 申请人并能够访问,但是在这种情况下,当我在我的 @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);
    }

}

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

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

我添加了它抱怨的 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.

我加了@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 我的回购TApplicantRepository 进入了它。

【问题讨论】:

  • 您的应用程序上下文文件在哪里?如果你没有,你应该考虑给 Spring 一些提示,比如 @ComponentScan 以使所有 bean 都可用。
  • @MarioSantini 请参阅更新 1
  • 我假设每次更新后错误都会发生变化?如果可能,请发布您的项目结构,以及每种情况下的错误日志/堆栈跟踪。最好知道“为什么”发生这些错误,而不是“某事”使错误消失。也会对遇到类似问题的其他人有所帮助。

标签: java spring-boot


【解决方案1】:

就我而言,我刚刚为一些类添加了@Component 注释(以确保每个类都有配置)。

@Component@Service@Repository 几乎是熟悉的。 Baeldung link reference

【讨论】:

    【解决方案2】:

    我有一个类似的问题,完全相同的错误消息。 但我的错误只发生在我尝试在本地 docker 上安装和运行时。

    原来这个问题取决于个人资料。

    我有两个实现接口的类,一个带有生产配置文件 @Profile("prod") 第二个是“测试环境”配置文件。 @Profile("!local & !prod")

    但是,当我尝试在本地(在 Docker 上)运行时,没有活动配置文件。

    我创建了第 3 个类,它为本地配置文件 @Profile("local") 实现了接口,这解决了我的问题

    【讨论】:

    【解决方案3】:

    由于@Repository 类的 basePackages 名称不正确,我在使用 MongoDB 时遇到了同样的问题

    @Configuration
    @EnableMongoRepositories(basePackages = {"org.mycompany.repository.mongo.primary"}, mongoTemplateRef = "getMongoTemplatePrimary")
    

    【讨论】:

      【解决方案4】:

      如果您正在使用 Eclipse 并尝试了所有可能性,但仍然有错误,请尝试使用 Maven 更新项目。你可以这样:Right click on your project-&gt; Maven -&gt; Update Project.

      它帮助我解决了我的错误。如果项目没有使用您在 pom 文件中声明的所有 repos 进行更新,有时 Eclipse 会显示此错误。

      【讨论】:

        【解决方案5】:

        当您未能使用 @Entity Annotation 注释与您的 bean 关联的实体类时,也会弹出此错误消息。

        我的ComponentScan 工作正常,但是@repository 界面弹出了这个:

        @Repository
        public interface ExpenseReportAuditRepository extends 
             PagingAndSortingRepository<ExpenseReportAudit, Integer> {
        

        因为我没有给ExpenseReportAudit添加@Entity注解

        @Entity // <--- Adding this fixed the issue.
        public class ExpenseReportAudit {
          .....
        

        【讨论】:

          【解决方案6】:

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

          【讨论】:

            【解决方案7】:

            在我的例子中,我们的项目有一个配置类,所以我只是像这样添加了我的

            @Configuration
            public class DependencyConfiguration {
            
                @Bean
                public ActivityService activityService(
                        @Value("${send.money.ms.activity.url}") final String activityHistoryUrl,
                        final HttpRestService httpRestService
                ) {
                    return new ActivityServiceImpl(activityHistoryUrl, httpRestService);
                }
            

            .......................

            然后微服务就正常启动了。

            PS:即使我需要的库已正确导入并且可以在导入的外部库中看到,我也遇到了这个问题。

            【讨论】:

              【解决方案8】:

              @Service应该从org.springframework.stereotype.Service导入

              您可能从org.jvnet.hk2.annotations.Service 导入它

              【讨论】:

                【解决方案9】:

                对我来说 - 使用 Spring Boot 和 MongoDB,以下是问题:

                在我的 POM.xml 中,我有:

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

                但我需要以下内容:

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

                (简短:添加“spring-boot-...”而不是仅“spring-...”)

                【讨论】:

                  【解决方案10】:

                  对我来说,在 pom.xml 上进行了全新安装

                  1. 右击 pom.xml

                  2. 展开运行方式

                  3. 选择 Maven 构建

                  4. 将目标设置为命令全新安装

                  5. 应用 > 运行 > 关闭

                  【讨论】:

                    【解决方案11】:

                    要修复以下错误:

                    我碰巧LocalContainerEntityManagerFactoryBean 类没有setPackagesToScan 方法。然后我继续使用无法正常工作的@EntityScan 注释。

                    后来我可以找到方法setPackagesToScan()但是在另一个模块中,所以问题出在依赖没有这个方法,因为它是一个旧版本。

                    这个方法可以在更新版本spring-data-jpaspring-orm依赖中找到:

                    发件人:

                    implementation("org.springframework", "spring-orm", "2.5.1") 
                    

                    收件人:

                    implementation("org.springframework", "spring-orm", "5.2.9.RELEASE")
                    

                    或者到:

                    implementation("org.springframework.data", "spring-data-jpa", "2.3.4.RELEASE")
                    

                    除此之外,不需要添加其他注释 @SprintBootApplication.

                    @SpringBootApplication
                    open class MoebiusApplication : SpringBootServletInitializer()
                    
                    @Bean
                    open fun entityManagerFactory() : LocalContainerEntityManagerFactoryBean {
                        val em = LocalContainerEntityManagerFactoryBean()
                        em.dataSource = dataSource()
                        em.setPackagesToScan("app.mobius.domain.entity")
                        ... 
                    }
                    

                    GL

                    Source

                    【讨论】:

                      【解决方案12】:

                      重要提示:

                      对于通过谷歌搜索通用 bean 错误消息而来到这里的任何人,但他们实际上正试图通过 @987654321 将 feign 客户端 添加到他们的 Spring Boot 应用程序中@ 注释在您的客户端界面上,以上解决方案都不适合您。

                      要解决此问题,您需要将@EnableFeignClients 注解添加到您的应用程序类中,如下所示:

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

                      旁注:在@SpringBootApplication 下添加@ComponentScan(...) 是多余的,您的 IDE 应该这样标记它(至少 IntelliJ IDEA 会这样做)。

                      【讨论】:

                      • 谢谢,这正是我遇到的@FeignClient 无法识别的问题。但是添加 EnableFeignClients 解决了这个问题。谢谢!
                      • 在我的情况下,我必须在 @EnableFeignClients 中指定包位置:例如 @EnableFeignClients ("com.myapp.client")
                      【解决方案13】:

                      将 Springbootapplication(application.java) 文件移动到另一个包解决了我的问题。将其与控制器和存储库分开。

                      【讨论】:

                      • 还提到 componentsscan(basePackages={" "," "} 来考虑你的控制器所在的包
                      【解决方案14】:

                      检查基础包名。如果包有不同的模块,不以基础包名为前缀。

                      【讨论】:

                        【解决方案15】:

                        提醒 spring 不扫描世界,它使用目标扫描,这意味着存储 springbootapplication 的包下的所有内容。 因此,可能会出现此错误“考虑在配置 [Spring-Boot] 中定义类型为 'package' 的 bean”,因为您在不同的 springbootapplication 包中有服务接口。

                        【讨论】:

                          【解决方案16】:

                          尝试如下配置项目结构:

                          将所有repo、service、packages放在主包的子包中:

                          package com.leisure.moviemax;  //Parent package
                                  
                          @SpringBootApplication
                          @PropertySource(value={"classpath:conf.properties"})
                              
                          public class MoviemaxApplication implements CommandLineRunner {
                                  
                          package com.leisure.moviemax.repo; //child package
                          
                          @Repository
                          public interface UsrRepository extends JpaRepository<UserEntity,String> {
                          

                          【讨论】:

                            【解决方案17】:

                            将@Service等注解类型配置从线程运行方法中移除。

                            @Service, @Component
                            

                            【讨论】:

                              【解决方案18】:

                              您有可能在实现接口之前尝试@autowired一个接口

                              示例解决方案:

                                  **HomeController.java**
                                  class HomeController{
                              
                                    @Autowired
                                    UserService userService;
                                  .....
                                  }
                              ----------------------------------------------------------------------
                                  **UserService.java** 
                                  public interface UserService {
                                      User findByUsername(String username);
                                  .....
                                  }
                              -----------------------------------------------------------------------
                                   **UserServiceImpl.java**
                                   @Service
                                   public class UserServiceImpl implements UserService{
                              
                                       public User findByUsername(String username) {
                                         return userDao.findByUsername(username);
                                       }
                                      ....
                                    }
                              
                              <i>This is not italic</i>, and [this is not a link](https://example.com)
                              

                              【讨论】:

                              • 请检查您是否错过了在您的接口实现类中添加Service注解。 @Service 公共类 FsProxyImpl 实现 FSStatusProxy { Override public void getFlightInfoWithConnectingGate(List flightDetailsList) { System.out.println("list val"+flightDetailsList.get(0).getArrivalStation()); } }
                              【解决方案19】:

                              当您使用每个示例 @EnableMongoRepositories(YOUR_MONGO_REPOSITORIES_PACKAGE) 并且后来您重命名包名称或将其移动到另一个地方时,也会出现问题。

                              在多模块 maven 项目和 spring boot 中经常遇到它

                              【讨论】:

                                【解决方案20】:

                                如果您使用interface,您可以使用@Repository 注释扩展CrudRepository&lt;Applicant,Long&gt;

                                【讨论】:

                                  【解决方案21】:

                                  我遇到了同样的问题。 Spring boot 识别了 Mongo DB 存储库,但它没有为扩展 mongo 存储库的存储库接口创建 Bean。

                                  在我的情况下,问题是 maven pom 中“spring + mango”的版本规范不正确。我已经更改了工件的组 ID,这一切都像魔术一样工作。不需要注释,因为 spring boot 处理了所有事情。

                                  在我解决问题的过程中,我在网上到处寻找解决方案,并意识到这个问题实际上与项目配置有关,任何遇到此问题的人都应该首先检查他们的项目设置并从 spring 启用调试以获取有关失败的更多详细信息并付费密切注意在这个过程中,创建失败的确切位置。

                                  【讨论】:

                                    【解决方案22】:

                                    它可能对某人有所帮助。我有同样的问题,同样的错误信息,同样的一切。我尝试了其他答案的解决方案,直到我意识到我正在使用的 bean 与实际自动装配的 bean 具有相同的名称时才有所帮助。它发生在重构过程中,因此我不得不重命名该类,结果是积极的。干杯

                                    【讨论】:

                                      【解决方案23】:

                                      添加 Spring Boot Data JPA Starter 依赖项为我解决了这个问题。

                                      Maven

                                      <dependency>
                                          <groupId>org.springframework.boot</groupId>
                                          <artifactId>spring-boot-starter-data-jpa</artifactId>
                                          <version>2.2.6.RELEASE</version>
                                      </dependency>
                                      

                                      Gradle

                                      compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '2.2.6.RELEASE'
                                      

                                      或者你可以直接去here

                                      【讨论】:

                                      • 这实际上不适用于这种情况。它提示输入到数据库的连接详细信息(无法配置数据源:未指定“url”属性并且无法配置嵌入式数据源。)。在我想手动测试而不与数据库交互的情况下,这是行不通的。
                                      【解决方案24】:

                                      我认为,您的 RequestController 中缺少 @Bean 注释

                                      在你的文件中添加 Bean,这解决了我的问题
                                      我在从 tutorialspoint 学习 Spring Boot 时得到了这个解决方案

                                      private Applicant applicant;
                                      
                                      @Bean 
                                      public Applicant applicant() { 
                                          return new Applicant(); 
                                      }
                                      

                                      【讨论】:

                                        【解决方案25】:

                                        我的错误是我包含了:

                                        <dependency>
                                            <groupId>org.springframework.data</groupId>
                                            <artifactId>spring-data-jpa</artifactId>
                                            <version>2.2.5.RELEASE</version>
                                        </dependency>
                                        

                                        代替:

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

                                        【讨论】:

                                          【解决方案26】:

                                          我在使用 Spring Boot 2 的 Maven 多模块项目中遇到了熟悉的问题。该问题与子 Maven 模块中的包命名有关。

                                          @SpringBootApplication 封装了很多组件,例如 - @ComponentScan、@EnableAutoConfiguration、jpa-repositories、json-serialization 等等。他将@ComponentScan 放在 com.*******.space 包中。这部分包 com.*******.space 必须是所有模块通用的。

                                          修复它:

                                          1. 您应该重命名所有模块包。换句话说,你必须在所有 Maven 模块中的所有包中都有 - 相同的父部分。例如 - com.*******.space
                                          2. 您还必须将您的入口点移动到此包 - com.*******.space

                                          【讨论】:

                                            【解决方案27】:

                                            如果您不小心在两个不同的类中定义了同一个 bean,您也会收到此错误。那发生在我身上。错误消息具有误导性。当我移除多余的 bean 后,问题就解决了。

                                            【讨论】:

                                              【解决方案28】:

                                              @Configuration 注解只会解决错误

                                              【讨论】:

                                                【解决方案29】:

                                                如果您的类依赖项由 Spring 管理,那么如果我们忘记在 POJO 类中添加默认/空 arg 构造函数,则可能会出现此问题。

                                                【讨论】:

                                                  【解决方案30】:

                                                  我有一个案例,我需要将 RestTemplate 注入服务类。但是,服务类无法获取 RestTemplate。我所做的是在与主应用程序相同的包下创建一个包装器类,并将包装器标记为 Component 并在服务类中自动装配该组件。问题解决了。希望它也适合你

                                                  【讨论】:

                                                    猜你喜欢
                                                    • 2021-04-04
                                                    • 2022-09-29
                                                    • 2018-06-22
                                                    • 1970-01-01
                                                    • 1970-01-01
                                                    • 2020-08-01
                                                    • 2019-02-14
                                                    • 2018-12-21
                                                    • 2019-05-10
                                                    相关资源
                                                    最近更新 更多