考虑定义一个类型为' package'的bean。在您的配置中[Spring-Boot]

时间:2016-11-02 15:42:58

标签: java 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;
}

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

}

------------------------ UPDATE 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()相关的所有内容时,我能够返回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。{/ p>

39 个答案:

答案 0 :(得分:131)

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

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

答案 1 :(得分:35)

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

假设您的main类&#34; WebServiceApplication&#34;在&#34; com.service.something&#34;,然后所有组件都属于&#34; com.service.something&#34;被扫描,&#34; com.service.applicant&#34;不会被扫描。

您可以重构您的软件包,以便&#34; WebServiceApplication&#34;属于根包,所有其他组件都成为该根包的一部分。或者您可以包含@SpringBootApplication(scanBasePackages={"com.service.something","com.service.application"})等,以便&#34; ALL&#34;组件在弹簧容器中进行扫描和初始化。

根据评论进行更新

如果您有多个由maven / gradle管理的模块,则所有弹簧需求都是要扫描的包。你告诉spring扫描&#34; com.module1&#34;并且您有另一个模块,其根包名称为&#34; com.module2&#34;,这些组件不会被扫描。您甚至可以告诉spring扫描&#34; com&#34; ,然后扫描&#34; com.module1.&#34;中的所有组件。和&#34; com.module2.&#34;

答案 2 :(得分:21)

有机会......
您可能在各自的实现类上缺少@Service@Repository注释。

答案 3 :(得分:14)

基本上,当您将“类应用程序”放在“另一个程序包”中时会发生这种情况。例如:

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

我在Application.class中解决了这个问题

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

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

答案 4 :(得分:5)

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

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

要修复它:

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

答案 5 :(得分:3)

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

答案 6 :(得分:3)

就我而言,我犯了一个严重的错误。我将@Service放在服务界面上。

要修复此问题,我在服务文件的实现中放了@Service,它对我有用。

答案 7 :(得分:2)

重要提示:

对于通过谷歌搜索通用bean错误消息而来到这里,但实际上正在尝试通过{{向其Spring Boot应用程序添加 虚假客户端 的任何人1}}在客户端界面上的注释,以上任何一种解决方案都无法为您服务。

要解决此问题,您需要向您的Application类添加@FeignClient批注,如下所示:

@EnableFeignClients

旁注:在@SpringBootApplication // ... (other pre-existing annotations) ... @EnableFeignClients // <------- THE IMPORTANT ONE public class Application { 下添加@ComponentScan(...) 是多余的 ,并且您的IDE应该对此进行标记(IntelliJ IDEA在至少)。

答案 8 :(得分:2)

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

答案 9 :(得分:1)

如果您无法使用 @Entity 注释注释与 bean 关联的实体类,也会弹出此错误消息。

我的 ComponentScan 工作正常,但在 @repository 界面中弹出:

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

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

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

答案 10 :(得分:1)

就我而言,我们的项目有一个 Configuration 类,所以我只是像这样添加了我的

@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:即使我需要的库已正确导入并且可以在导入的外部库中看到,我也遇到了这个问题。

答案 11 :(得分:1)

我遇到了同样的问题。 Spring引导确定了Mongo数据库存储库,但是它没有为扩展mongo存储库的存储库接口创建Bean。

在我的情况下,问题是Maven pom中“ spring + mango”的版本说明不正确。我已经更改了工件的组ID,所有这些都像魔术一样工作。不需要注释,因为Spring Boot可以处理所有事情。

在解决问题期间,我到处都是Web搜索解决方案,并意识到此问题实际上与项目配置有关,因此,面对此问题的任何人都应首先检查其项目设置并从spring启用调试以获取有关失败的更多详细信息并付费密切注意创建过程到底在哪里失败。

答案 12 :(得分:1)

这可能会对某人有所帮助。我有同样的问题,同样的错误信息,同样的东西。我尝试了其他答案的解决方案,直到我意识到所使用的Bean与实际上已自动接线的Bean具有相同的名称时才有用。它发生在重构期间,因此我不得不重命名该类,这产生了积极的结果。干杯

答案 13 :(得分:1)

我的错误是我包括了:

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

答案 14 :(得分:1)

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

答案 15 :(得分:1)

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

  

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

在我的情况下,错误告诉我问题所在的控制器是什么,在删除@NonNull后应用程序启动正常

答案 16 :(得分:1)

在应用程序中添加以下注释后,它对我有用:

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

我遇到以下错误:

  

“构造函数中的参数1需要找不到的映射器类型的bean:

答案 17 :(得分:1)

如果Bean与@Autowired位于同一包装中,则它将永远不会引起此类问题。但是,默认情况下无法从其他程序包访问bean。 要解决此问题,请按照以下步骤操作:

  1. 将以下内容导入您的主班:
    导入org.springframework.context.annotation.ComponentScan;
  2. 在您的主类上添加注释:
@ComponentScan(basePackages = {"your.company.domain.package"})
public class SpringExampleApplication {

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

答案 18 :(得分:1)

我在网上寻求答案,但似乎没有一个适当的解决方案来解决我的问题: 一开始,一切运作良好如下:

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

然后我试图添加一个地图来缓存一些东西,它变成了这个:

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

轰!

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.

我删除了@AllArgsConstructor(onConstructor = @__(@Autowired)),并为@Autowiredrepository添加serviceMap<String, String>除外。它就像以前一样工作。

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

希望这可能会有所帮助。

答案 19 :(得分:0)

从线程运行方法中删除注释类型配置,例如@Service。

<?import com.gluonhq.charm.glisten.control.Icon?>

<Icon content="FILE_DOWNLOAD" prefHeight="112.0" prefWidth="119.0" />

答案 20 :(得分:0)

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

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

答案 21 :(得分:0)

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

导入

您可能是从 org.jvnet.hk2.annotations.Service

导入的

答案 22 :(得分:0)

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

  1. 右键单击 pom.xml

  2. 展开运行方式

  3. 选择 Maven 构建

  4. 将目标设置为命令 clean install

  5. 应用 > 运行 > 关闭

答案 23 :(得分:0)

要修复以下错误:

我偶然发现LocalContainerEntityManagerFactoryBean类没有setPackagesToScan方法。然后,我继续使用@EntityScan注释,该注释无法正常工作。

稍后我可以在另一模块中找到方法setPackagesToScan(),因此问题出在依赖项上,因为它是旧版本,所以没有该方法。

可以在更新版本 spring-data-jpa spring-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

答案 24 :(得分:0)

如果@Service类标记为abstract,则会发生这种情况。

答案 25 :(得分:0)

检查基本程序包名称。如果程序包具有不带基本程序包名称前缀的其他模块。

答案 26 :(得分:0)

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

答案 27 :(得分:0)

尝试按如下所示配置项目结构:

将所有回购,服务,程序包放入主程序包的子程序包中:

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> {

答案 28 :(得分:0)

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

答案 29 :(得分:0)

在实现接口之前,您可能会尝试 @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)

答案 30 :(得分:0)

当您使用示例@EnableMongoRepositories(YOUR_MONGO_REPOSITORIES_PACKAGE)并随后重命名程序包名称或将其移动到另一个位置时,也会出现问题。

在多模块Maven项目和Spring Boot中经常遇到它

答案 31 :(得分:0)

如果您使用interface,则可以使用CrudRepository<Applicant,Long>注释扩展@Repository

答案 32 :(得分:0)

在我看来,这两个选项都有效。

    //@ComponentScan ({"myapp", "myapp.resources","myapp.services"})中的
  1. 在列表中包含 also 包含Application.class的软件包,或

  2. 只需添加@EnableAutoConfiguration;它会自动识别所有的四季豆。

答案 33 :(得分:0)

添加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>

成绩

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

或者您可以直接here

答案 34 :(得分:0)

我认为,您在RequestController中缺少@Bean批注

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

private Applicant applicant;

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

答案 35 :(得分:0)

在我的情况下,由于我的导入错误而出现此错误,例如,使用spring时,导入自动出现:

import org.jvnet.hk2.annotations.Service;

但是我需要:

import org.springframework.stereotype.Service;

答案 36 :(得分:0)

如果您不小心在两个不同的类中定义了相同的bean,也会收到此错误。那件事发生在我身上。该错误信息具有误导性。当我删除多余的bean时,问题已解决。

答案 37 :(得分:0)

@Configuration批注将解决错误

答案 38 :(得分:-1)

对我来说 - 在 MongoDB 中使用 Spring Boot,问题如下:

在我的 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-...”)