【问题标题】:Error: Field required a bean of type that could not be found. Consider defining a bean错误:字段需要找不到类型的 bean。考虑定义一个 bean
【发布时间】:2018-01-26 17:13:10
【问题描述】:

在 Spring Boot 1.5.9 上创建 Spring Boot 应用程序时,我收到以下错误消息。任何机构都可以帮忙吗?提前致谢。

  .   ____          _            __ _ _
     /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
    ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
     \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
      '  |____| .__|_| |_|_| |_\__, | / / / /
     =========|_|==============|___/=/_/_/_/
     :: Spring Boot ::        (v1.5.9.RELEASE)

    2018-01-26 22:16:01.534  INFO 7176 --- [           main] com.myapp.MyAppApplication               : Starting MyAppApplication on DESKTOP-29H8ALN with PID 7176 (F:\My_SpringBoot_WorkSpace_20_01_2018\MyApp\MyApp\target\classes started by Tanmoy in F:\My_SpringBoot_WorkSpace_20_01_2018\MyApp\MyApp)
    2018-01-26 22:16:01.534  INFO 7176 --- [           main] com.myapp.MyAppApplication               : No active profile set, falling back to default profiles: default
    2018-01-26 22:16:01.590  INFO 7176 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@61009542: startup date [Fri Jan 26 22:16:01 IST 2018]; root of context hierarchy
    2018-01-26 22:16:02.889  INFO 7176 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 9001 (http)
    2018-01-26 22:16:02.903  INFO 7176 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
    2018-01-26 22:16:02.904  INFO 7176 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.23
    2018-01-26 22:16:03.075  INFO 7176 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
    2018-01-26 22:16:03.075  INFO 7176 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1490 ms
    2018-01-26 22:16:03.238  INFO 7176 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
    2018-01-26 22:16:03.242  INFO 7176 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
    2018-01-26 22:16:03.243  INFO 7176 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
    2018-01-26 22:16:03.243  INFO 7176 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
    2018-01-26 22:16:03.243  INFO 7176 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
    2018-01-26 22:16:03.277  WARN 7176 --- [           main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'customerController': Unsatisfied dependency expressed through field 'customerService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'customerService': Unsatisfied dependency expressed through field 'customersRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.myapp.repository.CustomersRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    2018-01-26 22:16:03.278  INFO 7176 --- [           main] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
    2018-01-26 22:16:03.311  INFO 7176 --- [           main] utoConfigurationReportLoggingInitializer : 

    Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
    2018-01-26 22:16:03.396 ERROR 7176 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

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

    Description:

    Field customersRepository in com.myapp.service.CustomerService required a bean of type 'com.myapp.repository.CustomersRepository' that could not be found.


    Action:

    Consider defining a bean of type 'com.myapp.repository.CustomersRepository' in your configuration.

我正在使用这个设置:

  1. Spring Boot 1.5.9

  2. Oracle 11g 数据库。

请在 pom.xml 中找到我正在使用的以下类:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.tanmoy</groupId>
    <artifactId>MyApp</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>MyApp</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
            <exclusions>
                <exclusion>
                    <artifactId>hibernate-entitymanager</artifactId>
                    <groupId>org.hibernate</groupId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>12.1.0.1</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

Java 代码 - 应用程序:

package com.myapp;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

import com.myapp.entity.Customers;
import com.myapp.repository.CustomersRepository;
import com.myapp.service.CustomerService;

@SpringBootApplication
public class MyAppApplication {

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

    }

    @Bean
    public CommandLineRunner demo(CustomersRepository repository) {

        return (args) -> {

            // fetch all customers

            for (Customers customer : repository.findAll()) {

            }

        };

    }

}

Java 代码 - 存储库:

package com.myapp.repository;

import java.util.List;

import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import com.myapp.entity.Customers;

@Repository
public interface CustomersRepository extends CrudRepository<Customers, Integer> {

    @Query("select * from customers")
    public List<Customers> getAllCustomerts();

}

Java 代码 - 服务:

package com.myapp.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.myapp.repository.CustomersRepository;

@Service
public class CustomerService {

    @Autowired
    CustomersRepository customersRepository;

    public void getAllCustomers() {
        System.out.println(customersRepository.findAll());
    }

}

【问题讨论】:

  • 可以添加Customers类的内容吗?

标签: spring spring-boot spring-data spring-data-jpa


【解决方案1】:

从CustomersRepository 中删除@Repository 注释。

接口CrudRepository已经在Spring的容器中注册并且已经可以被注入(也是它的子接口)。

【讨论】:

  • 您好,感谢您的回复,但删除 @Repository 后,我仍然遇到同样的错误。
【解决方案2】:

我认为异常堆栈跟踪中还有更多未共享的异常,我认为异常将指向错误的查询。 CustomersRespository 中的查询应如下所示:

@Query("select c from Customers c")
public List<Customers> getAllCustomerts();

【讨论】:

  • 您好感谢您的回复,更改查询后我遇到了同样的问题:(
【解决方案3】:

如果您从不使用它,为什么要在存储库中定义 getAllCustomers? CrudRepository 已经免费为您提供了一些有用的方法实现,除了接口声明之外,您无需编写任何代码。 我的建议是删除存储库中的 getAllCustumers 并从服务中调用存储库上的 findAll。

【讨论】:

    【解决方案4】:
    @Autowired
    CustomersRepository customersRepository;
    

    这不是 Autowire 的正确方法。这是:

    CustomersRepository customersRepository;
    
    @Autowire
    public defaultConstructor(CustomerRepository customerRepository){
    this.customerRepository = customerRepository;
    }
    

    注意: defaultConstructor 只是你的类名(默认构造函数)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-25
      • 2021-09-21
      • 2018-08-03
      • 1970-01-01
      • 2021-07-23
      • 2021-05-25
      • 2019-12-05
      • 2019-10-21
      相关资源
      最近更新 更多