简体   繁体   English

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

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

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.我以前从未见过此错误,但奇怪的是 @Autowire 无法正常工作。 Here is the project structure:这是项目结构:

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 Applicant in the RestController prior to adding @ComponentScan() I was able to return a string the UI , thus meaning my RestController was working, now it is being skipped.但是,当我在添加@ComponentScan()之前在RestController中注释掉与Applicant打交道的所有内容时,我能够返回一个字符串UI ,这意味着我的RestController正在工作,现在它被跳过了。 I ugly Whitelabel Error Page now.我现在丑陋Whitelabel Error Page

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

I added the base package of the bean it was complaining about.我添加了它所抱怨的 bean 的基数 package。 Error reads:错误内容如下:

***************************
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 ApplicantImpl class which @Autowires my repo TApplicantRepository into it.仍然在抱怨我的ApplicantImpl class,@ @Autowires我的回购TApplicantRepository到它。

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 {

There is a chance...有机会...
You might be missing @Service , @Repository or @Component annotation on your respective implementation classes.您可能在各自的实现类上缺少@Service@Repository@Component注释。

Your Applicant class is not scanned it seems.您的申请人类似乎没有被扫描。 By default all packages starting with the root as the class where you have put @SpringBootApplication will be scanned.默认情况下,所有以根作为您放置@SpringBootApplication的类的包都将被扫描。

suppose your main class "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.您可以重组您的包,使“WebServiceApplication”属于根包,而所有其他组件都成为该根包的一部分。 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.或者您可以包含@SpringBootApplication(scanBasePackages={"com.service.something","com.service.application"})等,以便在 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.如果您有多个由 maven/gradle 管理的模块,则所有 spring 需要的是要扫描的包。 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.您告诉 spring 扫描“com.module1”并且您有另一个模块,其根包名称为“com.module2”,这些组件将不会被扫描。 You can even tell spring to scan "com" which will then scan all components in " com.module1. " and " com.module2. "你甚至可以告诉 spring 扫描“com” ,然后扫描“ com.module1. ”和“ com.module2. ”中的所有组件。

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.另一种不太优雅的方法是:将所有配置类放在同一个包中。

In my case I had a terrible mistake.就我而言,我犯了一个可怕的错误。 I put @Service up to the service interface.我把@Service放到了服务接口上。

To fix it, I put @Service on the implementation of service file and it worked for me.为了解决这个问题,我将@Service放在服务文件的实现上,它对我有用。

If a bean is in the same package in which it is @Autowired, then it will never cause such an issue.如果 bean 与 @Autowired 在同一个包中,那么它永远不会导致这样的问题。 However, beans are not accessible from different packages by default.但是,默认情况下,无法从不同的包访问 bean。 To fix this issue follow these steps :解决此问题,请执行以下步骤:

  1. Import following in your main class:在您的主类中导入以下内容:
    import org.springframework.context.annotation.ComponentScan;导入 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);
    }
}

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.如果您使用 Lombok 并且为字段添加了@RequiredArgsConstructor@NonNull但您的某些字段不会注入到构造函数中,也会发生这种情况。 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参数 0 需要一个无法找到的 MissingBeanName 类型的 bean

In my case the error told me what Controller the problem was in, after removing @NonNull the application started fine在我的情况下,错误告诉我问题出在哪个控制器上,删除@NonNull后应用程序开始正常

I faced with familiar problem in my Maven multi-module project with Spring Boot 2. The problem was related to naming of my packages in sub Maven modules.我在使用 Spring Boot 2 的 Maven 多模块项目中遇到了熟悉的问题。该问题与子 Maven 模块中的包命名有关。

@SpringBootApplication incapsulate a lots of component like - @ComponentScan, @EnableAutoConfiguration, jpa-repositories, json-serialization and so on. @SpringBootApplication 封装了很多组件,例如 - @ComponentScan、@EnableAutoConfiguration、jpa-repositories、json-serialization 等等。 And he places @ComponentScan in com.*******.space package.他将@ComponentScan 放在 com.*******.space 包中。 This part of packages com.*******.space must be common for all modules.这部分包 com.*******.space 必须是所有模块通用的。

For fixing it:为了修复它:

  1. You should rename all module packages.您应该重命名所有模块包。 Other words you had to have in all packages in all Maven modules - the same parent part.换句话说,您必须在所有 Maven 模块中的所有包中都有 - 相同的父部分。 For example - com.*******.space例如 - com.*******.space
  2. Also you have to move your entry point to this package - com.*******.space此外,您必须将您的入口点移动到此包 - com.*******.space

Important:重要的:

For anybody who was brought here by googling the generic bean error message, but who is actually trying to add a feign client to their Spring Boot application via the @FeignClient annotation on your client interface, none of the above solutions will work for you.对于通过谷歌搜索通用 bean 错误消息而被带到这里的任何人,但实际上是试图通过客户端界面上的@FeignClient注释将 feign客户端添加到他们的 Spring Boot 应用程序,上述解决方案都不适合您。

To fix the problem, you need to add the @EnableFeignClients annotation to your Application class, like so:要解决此问题,您需要将@EnableFeignClients注释添加到您的 Application 类中,如下所示:

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

Side note: adding a @ComponentScan(...) beneath @SpringBootApplication is redundant , and your IDE should flag it as such (IntelliJ IDEA does, at least).旁注:在@SpringBootApplication下添加@ComponentScan(...)是多余的,您的 IDE 应该这样标记它(至少 IntelliJ IDEA 会这样做)。

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

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//@ComponentScan ({"myapp", "myapp.resources","myapp.services"})包括在列表中包含Application.class的包,或者

  2. Simply add @EnableAutoConfiguration ;只需添加@EnableAutoConfiguration it automatically recognizes all the spring beans.它会自动识别所有的弹簧豆。

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: “构造函数的参数 1 需要一个找不到的映射器类型的 bean:

Moving the Springbootapplication(application.java) file to another package resolved the issue for me.将 Springbootapplication(application.java) 文件移动到另一个包解决了我的问题。 Keep it separate from the controllers and repositories.将其与控制器和存储库分开。

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> .我删除了@AllArgsConstructor(onConstructor = @__(@Autowired))并为除Map<String, String>之外的每个repositoryservice添加@Autowired 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.希望这可能会有所帮助。

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

In my case this error appear because my import was wrong, for example, using spring, the import automatically appear:就我而言,出现此错误是因为我的导入错误,例如,使用 spring,导入会自动出现:

import org.jvnet.hk2.annotations.Service;

but i needed:但我需要:

import org.springframework.stereotype.Service;

@Configuration 注释只会解决错误

You'll also get this error if you accidentally define the same bean in two different classes.如果你不小心在两个不同的类中定义了同一个 bean,你也会得到这个错误。 That happened to me.那发生在我身上。 The error message was misleading.错误消息具有误导性。 When I removed the extra bean, the issue was resolved.当我删除额外的 bean 时,问题就解决了。

My error was that I had included:我的错误是我包括了:

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

instead of:代替:

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

I faced the same issue.我遇到了同样的问题。 Mongo DB repository was identified by Spring boot, but it was not creating Bean for a repository interface that extended the mongo repository. Mongo DB 存储库由 Spring boot 识别,但它没有为扩展 mongo 存储库的存储库接口创建 Bean。

The issue in my case was incorrect version specification in maven pom for "spring + mango".在我的情况下,问题是 maven pom 中“spring + mango”的版本规范不正确。 I have changed the artifact's group id and it all worked like magic.我已经更改了工件的组 ID,这一切都像魔术一样工作。 no annotations needed as spring boot took care of everything.不需要注释,因为 spring boot 处理了所有事情。

During my problem resolution, I was all over web searching for solutions and realized that this problem is actually project configuration related, anyone facing this issue should first check their project setup and enable debug from spring to get more details on failure and pay close attention to where exactly in the process, the creation has failed.在我的问题解决过程中,我在网上搜索解决方案并意识到这个问题实际上与项目配置有关,任何遇到此问题的人都应该首先检查他们的项目设置并从 spring 启用调试以获取更多关于失败的详细信息并密切关注正是在这个过程中,创建失败了。

Try configuring the project structure as given below:尝试配置项目结构,如下所示:

Put all the repo, service, packages in the child package of the main package:将所有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> {

This error message also pops up when you fail to annotate the Entity classes associated with your bean with the @Entity Annotation .当您未能使用@Entity Annotation 注释与您的 bean 关联的实体类时,也会弹出此错误消息。

My ComponentScan worked fine but this popped up for the @repository interface:我的ComponentScan工作正常,但@repository接口弹出了这个:

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

because I failed to add the @Entity annotation to ExpenseReportAudit因为我未能将 @Entity 注释添加到ExpenseReportAudit

@Entity // <--- Adding this fixed the issue.
public class ExpenseReportAudit {
  .....
@SpringBootApplication
@MapperScan("com.developer.project.mapper")

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

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

It might help somebody.它可能会帮助某人。 I had the same problem, same error message, same everything.我有同样的问题,同样的错误信息,同样的一切。 I tried solutions from other answers, didn't help until I realised that the bean I am using has the same name as the one that is actually been autowired.我尝试了其他答案的解决方案,直到我意识到我正在使用的 bean 与实际自动装配的 bean 具有相同的名称时才有所帮助。 It happened in the midst of refactor, thus I had to rename the class, which resulted positively.它发生在重构过程中,因此我不得不重命名该类,结果是积极的。 Cheers干杯

In my case, our project has a Configuration class, so I just added mine like this就我而言,我们的项目有一个配置类,所以我只是像这样添加了我的

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

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

Then the microservice started alright.然后微服务就正常启动了。

PS: I encountered this issue even though the library I need is imported properly and could be seen on External Libraries imported. PS:即使我需要的库已正确导入并且可以在导入的外部库中看到,我也遇到了这个问题。

有同样的错误,表明这是应用程序属性的问题,用户名、密码和驱动程序不正确,与 Bean 完全无关。

I also received a similar error:我也收到了类似的错误:

Consider defining a bean of type 'A_REPOSITORY_INTERFACE' in your configuration.

Then, according to Akash e's solution , I added @EnableJpaRepositories to my main class. After that, I received the following error instead:然后,根据Akash e的解决方案,我将@EnableJpaRepositories添加到我的主class。之后,我收到了以下错误:

Consider defining a bean of type 'entityManagerFactory' in your configuration.

Next, I went through all the responses here, googled a lot and read a lot of other resources, which didn't worked out.接下来,我浏览了这里的所有回复,在谷歌上搜索了很多,并阅读了很多其他资源,但没有成功。

Finally, I was lucky to have found the solution on a blog/website (javatute.com) .最后,我很幸运在博客/网站(javatute.com)上找到了解决方案。 I just followed its examples.我只是按照它的例子。

Like suggested by many here, I added @ComponentScan("YOUR_BASE_PACKAGE.*") and @EntityScan("YOUR_BASE_PACKAGE.*") to my main app class, followed by adding a config package and creating a JpaConfig class like:正如这里许多人所建议的那样,我将@ComponentScan("YOUR_BASE_PACKAGE.*")@EntityScan("YOUR_BASE_PACKAGE.*")添加到我的主应用程序 class,然后添加config package 并创建JpaConfig class,例如:

package YOUR_BASE_PACKAGE.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@Configuration
@EnableJpaRepositories(basePackages = "YOUR_BASE_PACKAGE")
public class JpaConfig {

}

The blog I followed:我关注的博客:

Consider defining a bean of type in your configuration 考虑在您的配置中定义一个类型的 bean

which lead me to:这导致我:

Error creating bean with name entityManagerFactory defined in class path resource: Invocation of init method failed 在 class 路径资源中创建名称为 entityManagerFactory 的 bean 时出错:调用 init 方法失败

and finally to:最后到:

Many To Many Mapping In Hibernate/JPA Using Spring Boot And Oracle 使用 Spring Boot 和 Oracle 在 Hibernate/JPA 中进行多对多映射

I had a case where i need to inject RestTemplate into a service class.我有一个案例,我需要将 RestTemplate 注入服务类。 However, the RestTemplate cannot be picked up by the service class.但是,服务类无法获取 RestTemplate。 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.我所做的是在与主应用程序相同的包下创建一个包装器类,并将包装器标记为 Component 并在服务类中自动装配该组件。 Problem solved.问题解决了。 hope it also works for you希望它也适合你

I think, you are missing the @Bean annotation in your RequestController我认为,您在 RequestController 中缺少 @Bean 注释

Add the Bean in your file, this solved my issue在您的文件中添加 Bean,这解决了我的问题
I got this solution while I was learning Spring Boot from tutorialspoint我在从 tutorialspoint 学习 Spring Boot 时得到了这个解决方案

private Applicant applicant;

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

Adding Spring Boot Data JPA Starter dependency solved the issue for me.添加 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'

Or you can go directly here或者你可以直接去这里

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

Issue can also appeared when you use per example @EnableMongoRepositories(YOUR_MONGO_REPOSITORIES_PACKAGE) and later you renamed the package name or moved it in another place.当您使用每个示例@EnableMongoRepositories(YOUR_MONGO_REPOSITORIES_PACKAGE)并且稍后您重命名包名称或将其移动到另一个位置时,也会出现问题。

Very often faced it within a multi-module maven project and spring boot经常在多模块 Maven 项目和 Spring Boot 中遇到它

There is a chance that you are trying to @autowired an interface before implement the interface.您有可能在实现接口之前尝试@autowired接口。

example solution:示例解决方案:

    **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, @Component

reminder that spring doesn't scan the world , it uses targeted scanning wich means everything under the package where springbootapplication is stored.提醒一下 spring 不会扫描世界,它使用有针对性的扫描,这意味着存储 springbootapplication 的包下的所有内容。 therefore this error "Consider defining a bean of type 'package' in your configuration [Spring-Boot]" may appear because you have services interfaces in a different springbootapplication package .因此,可能会出现此错误“考虑在配置 [Spring-Boot] 中定义 'package' 类型的 bean”,因为您在不同的 springbootapplication 包中有服务接口。

检查基本包名称。如果包有不同的模块,这些模块没有以基本包名称为前缀。

To fix errors like:要修复以下错误:

It happened to me that the LocalContainerEntityManagerFactoryBean class did not have the setPackagesToScan method.我碰巧LocalContainerEntityManagerFactoryBean类没有setPackagesToScan方法。 Then I proceeded to use the @EntityScan annotation which doesn't work correctly.然后我继续使用无法正常工作的@EntityScan注释。

Later I could find the method setPackagesToScan() but in another module, so the problem came from the dependency which did not have this method because it was an old version.后来我可以找到方法setPackagesToScan()但在另一个模块中,所以问题来自没有此方法的依赖项,因为它是旧版本。

This method can be found in the spring-data-jpa or spring-orm dependency of updated versions :此方法可以在更新版本spring-data-jpaspring-orm依赖项中找到:

From:从:

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

To:至:

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

Or to:或者:

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

In addition, it was not necessary to add other annotations other than that of @SprintBootApplication .此外,除了@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 资源

For me worked a clean install on pom.xml对我来说,在 pom.xml 上进行了全新安装

  1. right click on pom.xml右键单击 pom.xml

  2. expand Run As展开运行方式

  3. select Maven build选择 Maven 构建

  4. set Goals to the command clean install将目标设置为命令clean install

  5. apply > run > close应用 > 运行 > 关闭

If you are using Eclipse and tried all possibilities and you still have errors, then try to update the project using Maven.如果您正在使用 Eclipse 并尝试了所有可能性,但仍然有错误,请尝试使用 Maven 更新项目。 You can to this like this: Right click on your project-> Maven -> Update Project .您可以这样: Right click on your project-> Maven -> Update Project

It helped me to solve my errors.它帮助我解决了我的错误。 Sometimes Eclipse shows this error if a project is not updated with all repos which you declared in the pom file.如果项目未使用您在 pom 文件中声明的所有 repos 更新,有时 Eclipse 会显示此错误。

I had the same issue while using MongoDB due to incorrect basePackages name of the @Repository class由于@Repository 类的basePackages 名称不正确,我在使用MongoDB 时遇到了同样的问题

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

I had a similar issue, exact same error message.我有一个类似的问题,完全相同的错误消息。 But my error only happened when I tried to install and run on my local docker.但是我的错误只发生在我尝试在本地 docker 上安装和运行时。

Turns out the issue was profile dependant.原来这个问题取决于个人资料。

I had two classes that implemented the interface, one with a production Profile @Profile("prod") and the second with the "Test Environment" profiles.我有两个实现接口的类,一个带有生产配置文件@Profile("prod"),第二个带有“测试环境”配置文件。 @Profile("!local & !prod") @Profile("!local & !prod")

However, there was no active profile for when I tried to run locally (on Docker).但是,当我尝试在本地(在 Docker 上)运行时没有活动配置文件。

I created a 3rd class that implemented the interface for a local profile @Profile("local") and this fixed my issue我创建了一个为本地配置文件 @Profile("local") 实现接口的第三类,这解决了我的问题

In my case, I have just added @Component annotations to some classes (to make sure every Classes have configuration).就我而言,我刚刚为某些类添加了@Component注释(以确保每个类都有配置)。

@Component , @Service or @Repository are almost familiar. @Component@Service@Repository几乎很熟悉。 Baeldung link reference Baeldung链接参考

In my case, this problem was caused by an errant spring.autoconfigure.exclude property value.就我而言,这个问题是由错误的spring.autoconfigure.exclude属性值引起的。 I had this property because my Spring Boot project initially didn't connect to a database, but then I added my first JpaRepository class and tried to declare an instance of it with the @Autowired annotation in a @RestController class.我有这个属性是因为我的 Spring Boot 项目最初没有连接到数据库,但后来我添加了我的第一个JpaRepository类并尝试在@RestController类中使用@Autowired注释声明它的一个实例。

The line in application.properties that caused the problem: application.properties中导致问题的行:

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration

Once I deleted or commented out that line, my Spring Boot service ran just fine.一旦我删除或注释掉该行,我的 Spring Boot 服务就运行得很好。

For me, it was because of using @Value in class that use lombok @RequiredArgsConstructor annotation.对我来说,这是因为在使用lombok @RequiredArgsConstructor注释的类中使用了@Value。 Just changed it to constructor injection.只是将其更改为构造函数注入。

I had the same problem, i was get this error for redis repository like this:我遇到了同样的问题,我在 redis 存储库中遇到了这个错误,如下所示:

@Repository
public interface AppTokenRepository extends CrudRepository<AppToken, String> {
}


@RedisHash("APP_TOKEN")
public class AppToken implements Serializable {
    private String id;
    private String accessToken;
}

I solved my issue by adding @EnableRedisRepositories over spring boot application class.我通过在 Spring Boot 应用程序类上添加@EnableRedisRepositories解决了我的问题。

@SpringBootApplication
@EnableFeignClients
@EnableEurekaClient
@EnableHystrix
@EnableHystrixDashboard
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

I fix it by add this config to Application.java file.我通过将此配置添加到 Application.java 文件来修复它。

在此处输入图像描述

This can also happen if you have two beans with the same name .如果您有两个同名bean ,也会发生这种情况。

For example if you have factory method monkey creating Monkey and you mistakenly name another factory method (creating Car) also monkey .例如,如果您有工厂方法monkey创建 Monkey 并且您错误地将另一个工厂方法(创建 Car)命名为monkey

Problematic code:有问题的代码:

    @Bean
    public Car monkey() {
        return new Car();
    }

Should be:应该:

    @Bean
    public Car car() {
        return new Car();
    }

Reference:参考:

By default, the bean name will be the same as the method name...默认情况下,bean 名称将与方法名称相同...

Spring doc 1 Spring 文档 1

Autowiring by property name.按属性名称自动装配。 Spring looks for a bean with the same name as the property that needs to be autowired. Spring 查找与需要自动装配的属性同名的 bean。 For example, if a bean definition is set to autowire by name and it contains a master property (that is, it has a setMaster(..) method), Spring looks for a bean definition named master and uses it to set the property.例如,如果一个 bean 定义被设置为按名称自动装配并且它包含一个 master 属性(也就是说,它有一个 setMaster(..) 方法),Spring 查找一个名为 master 的 bean 定义并使用它来设置该属性。

Spring doc 2 Spring 文件 2

Use @Component for the Class where the Bean is not found.对于没有找到 Bean 的 Class 使用@Component And Use并使用

@ComponentScan("<Use_The_Root_Directory_Of_Main_Class>") @ComponentScan("<Use_The_Root_Directory_Of_Main_Class>")

. . This can happen when the Components are spread over many directories.当组件分布在许多目录中时,可能会发生这种情况。

@Configuration
@SpringBootApplication
@ComponentScan({"com.example.demo"})
public class Application {
}

For me - using Spring Boot with MongoDB, the following was the Problem:对我来说 - 使用 Spring Boot 和 MongoDB,以下是问题:

In my POM.xml I had:在我的 POM.xml 中,我有:

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

but I needed the following:但我需要以下内容:

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

(Short: Add "spring-boot-..." instead of only "spring-...") (简短:添加“spring-boot-...”而不是仅“spring-...”)

@Service should be imported from org.springframework.stereotype.Service @Service应该从org.springframework.stereotype.Service导入

you might be importing it from org.jvnet.hk2.annotations.Service您可能从org.jvnet.hk2.annotations.Service导入它

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 考虑在您的配置中定义一个“服务”类型的 bean [Spring boot] - Consider defining a bean of type 'service' in your configuration [Spring boot] 考虑在配置中定义“包”类型的bean - Consider defining a bean of type 'package' in your configuration Spring Boot:考虑在配置中定义一个名为“ entityManagerFactory”的bean - Spring Boot: Consider defining a bean named 'entityManagerFactory' in your configuration 考虑在您的配置-Spring 启动中定义一个名为“entityManagerFactory”的 bean - Consider defining a bean named 'entityManagerFactory' in your configuration-Spring boot Java Spring 引导:考虑在配置中定义一个名为“entityManagerFactory”的bean - Java Spring Boot: Consider defining a bean named 'entityManagerFactory' in your configuration Spring 引导 - 将存储库注入 Controller 抛出考虑在配置中定义类型为“Type”的 bean - Spring Boot - Injecting Repository into Controller throws Consider defining a bean of type 'Type' in your configuration Spring 引导/MVC:考虑在配置中定义类型为“pack.website.repositories.CustomerRepository”的 bean - Spring Boot/MVC: Consider defining a bean of type 'pack.website.repositories.CustomerRepository' in your configuration 春季启动:考虑在配置中定义类型为“ com.repository.services.interfacename”的bean - Spring boot: Consider defining a bean of type 'com.repository.services.interfacename' in your configuration 考虑在你的配置中定义一个类型为 * 的 bean - Consider defining a bean of type * in your configuration 考虑在你的配置中定义一个 'form' 类型的 bean - Consider defining a bean of type 'form' in your configuration
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM