简体   繁体   English

Spring boot 中自动装配接口错误

[英]autowiring an interface Error in Spring boot

I'm currently facing this problem in Spring Boot when it comes to wiring a repository interface to a service class.在将存储库接口连接到服务类时,我目前在 Spring Boot 中面临这个问题。 here's my Item class package com.ensa.entity;这是我的 Item 类包 com.ensa.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Item {

    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private float prix;

    public Item(Long id,String name,float prix) {
        this.id=id;
        this.name=name;
        this.prix=prix;
    }
    public Item() {

    }
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public float getPrix() {
        return prix;
    }
    public void setPrix(float prix) {
        this.prix = prix;
    }}

here's my repository Interface这是我的存储库界面

package com.ensa.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.ensa.entity.Item;



@Repository
@Component
public interface ItemRepository extends JpaRepository<Item, Long> {

}

my Service class:我的服务类:

package com.ensa.service;

import java.util.ArrayList;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ensa.entity.Item;
import com.ensa.repository.ItemRepository;

@Service
@Transactional
public class ItemService {

    @Autowired
    private ItemRepository itemRepo ;


    private List<Item> list = new ArrayList<Item>();

    public ItemService() {
        Item A= new Item(1L,"AAAA",2);
        list.add(A);
        //itemRepo.count();
    }

    public List<Item> getAllItems() {     //Returning all Items


        return  list;
    }


    public Item getItemById(Long id) {    //getting Item by Id

        return null;

    }

    public void addItem(Item item) {    //adding new item
        list.add(item);


    }

    public void updateItem(Long id, Item item) {        //updating an existing Item
        itemRepo.save(item);



    }

    public void deleteItem(Long id) {       //deleting Item by id

        for (Item temp : list) {

            if (temp.getId() == id) {
                int i = list.indexOf(temp);
                list.remove(i);
                return;
            }

        }
    }
}

I was working with a list to test out the REST api but once I added the repository I started getting this error我正在使用一个列表来测试 REST api,但是一旦我添加了存储库,我就开始收到此错误

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

2020-03-05 10:19:41.426  INFO 468 --- [           main] com.ensa.app.SpringApp                   : Starting SpringApp on DESKTOP-FPSG9AG with PID 468 (C:\Users\perso\eclipse-workspace\springTest\target\classes started by perso in C:\Users\perso\eclipse-workspace\springTest)
2020-03-05 10:19:41.430  INFO 468 --- [           main] com.ensa.app.SpringApp                   : No active profile set, falling back to default profiles: default
2020-03-05 10:19:42.226  INFO 468 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2020-03-05 10:19:42.252  INFO 468 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 17ms. Found 0 repository interfaces.
2020-03-05 10:19:42.680  INFO 468 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$d295b9fe] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-03-05 10:19:43.105  INFO 468 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2020-03-05 10:19:43.152  INFO 468 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2020-03-05 10:19:43.153  INFO 468 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.16]
2020-03-05 10:19:43.161  INFO 468 --- [           main] o.a.catalina.core.AprLifecycleListener   : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [C:\Program Files\Java\jdk-13.0.1\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Java/jdk-13.0.1/bin/server;C:/Program Files/Java/jdk-13.0.1/bin;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;c:\Program Files (x86)\Microsoft SQL Server\110\Tools\Binn\;c:\Program Files\Microsoft SQL Server\110\Tools\Binn\;c:\Program Files\Microsoft SQL Server\110\DTS\Binn\;c:\Program Files (x86)\Microsoft SQL Server\110\Tools\Binn\ManagementStudio\;c:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\PrivateAssemblies\;c:\Program Files (x86)\Microsoft SQL Server\110\DTS\Binn\;C:\Program Files\Java\jdk-13.0.1\bin;C:\Program Files\apache-maven-3.6.3\bin;;C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2019.3.3\bin;;C:\Users\perso\OneDrive\Bureau;;.]
2020-03-05 10:19:43.352  INFO 468 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2020-03-05 10:19:43.352  INFO 468 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1873 ms
2020-03-05 10:19:43.563  INFO 468 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2020-03-05 10:19:43.705  INFO 468 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2020-03-05 10:19:43.765  INFO 468 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
2020-03-05 10:19:43.849  INFO 468 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.3.7.Final}
2020-03-05 10:19:43.851  INFO 468 --- [           main] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2020-03-05 10:19:44.022  INFO 468 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2020-03-05 10:19:44.190  INFO 468 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2020-03-05 10:19:44.538  INFO 468 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-03-05 10:19:44.584  WARN 468 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'itemController': Unsatisfied dependency expressed through field 'itemServ'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'itemService': Unsatisfied dependency expressed through field 'itemRepo'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.ensa.repository.ItemRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
2020-03-05 10:19:44.584  INFO 468 --- [           main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2020-03-05 10:19:44.589  INFO 468 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2020-03-05 10:19:44.602  INFO 468 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.
2020-03-05 10:19:44.603  INFO 468 --- [           main] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2020-03-05 10:19:44.619  INFO 468 --- [           main] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-03-05 10:19:44.781 ERROR 468 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

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

Description:

Field itemRepo in com.ensa.service.ItemService required a bean of type 'com.ensa.repository.ItemRepository' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)


Action:

Consider defining a bean of type 'com.ensa.repository.ItemRepository' in your configuration.

**

Any ideas on how to solve this problem?关于如何解决这个问题的任何想法?

You don't need to add @Repository or @Component on repository class.您不需要在存储库类上添加@Repository@Component Remove those annotation from repository.从存储库中删除这些注释。 Just use like只需使用像

public interface ItemRepository extends JpaRepository<Item, Long> {

}

And try replacing itemRepo with itemRepository .并尝试用itemRepo替换itemRepository So it will be like所以它会像

@Autowired
private ItemRepository itemRepository;

use @EnableJPArepository("com.ensa.repository") in main class, it might work, if not try to use below line在主类中使用@EnableJPArepository("com.ensa.repository") ,它可能会工作,如果不尝试使用下面的行

@ComponentScan("com.ensa.repository") in your service class it might works @ComponentScan("com.ensa.repository")在您的服务类中它可能有效

The @Repository is already a Stereotype annotation and so you don't need @Component with it. @Repository已经是一个Stereotype注释,所以你不需要@Component了。 You can remove the @Component annotation from your Repository .您可以从Repository删除@Component注释。

@Repository
public interface ItemRepository extends JpaRepository<Item, Long> {

}

Also, It is not a good practice to use @Transactional on an entire class as it will slow down your code because database requires a lock for the time your entire code annotated with @Transactional executes.此外,在整个类上使用@Transactional也不是一个好习惯,因为它会减慢您的代码速度,因为数据库需要在用@Transactional注释的整个代码执行时锁定。

While the others are right, and you could leave out @Component on @Repository, your actual error is that the @Bean could not be found.虽然其他人是对的,并且您可以在@Repository 上省略@Component,但您的实际错误是无法找到@Bean。

  1. @SpringBootApplication (the annotation on your main class) includes a @ComponentScan , which means Spring will scan all classes in the same package all subpackages for annotations/beans ( like @Component..or @Repository). @SpringBootApplication(主类上的注释)包含一个@ComponentScan ,这意味着 Spring 将扫描同一个包中的所有类,所有子包中的注释/bean(如 @Component.. 或 @Repository)。
  2. Make sure that your repository class is in the same package OR in a sub-package, not in a sibling-package.确保您的存储库类在同一个包中或在子包中,而不是在同级包中。 Otherwise, it cannot be found or you would have to modify your ComponentScan.否则,无法找到它,或者您必须修改您的 ComponentScan。
  3. Then it should be found.那么应该可以找到。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM