错误:字段需要无法找到的bean类型。考虑定义一个bean

时间:2018-01-26 17:13:10

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

在Spring boot 1.5.9上创建Spring启动应用程序时,我收到以下错误消息。有人可以帮忙吗?提前谢谢。

  .   ____          _            __ _ _
     /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
    ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
     \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
      '  |____| .__|_| |_|_| |_\__, | / / / /
     =========|_|==============|___/=/_/_/_/
     :: 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数据库。

  3. 请找到我正在使用的以下类和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());
        }
    
    }
    

4 个答案:

答案 0 :(得分:0)

@Repository删除CustomersRepository注释。

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

答案 1 :(得分:0)

我认为异常堆栈跟踪中有更多内容未共享,我认为异常将指向不正确的查询。 CustomersRespository中的查询应如下所示:

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

答案 2 :(得分:0)

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

答案 3 :(得分:-1)

@Autowired
CustomersRepository customersRepository;

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

CustomersRepository customersRepository;

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

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