“”中的字段存储库需要一个名为 'entityManagerFactory' 的 bean,但找不到

Field repository in '' required a bean named 'entityManagerFactory' that could not be found

所以我已经学习 Spring 几周了。我正在尝试制作一个涉及 Controller -> Service -> Repository -> Database 模式的简单项目。

我开始遇到这个问题,但找不到解决方法。我在网上偶然发现了一些类似的问题并出现了同样的错误,但是其中 none 给出了我的解决方案,在我的项目中一切似乎都很正常。

这是输出错误:

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

Description:

Field repository in com.Library.services.LibraryService required a bean named 'entityManagerFactory' 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 named 'entityManagerFactory' in your configuration.

这是我项目的文件(文件树):

这是我的代码:

主要class:

package com.Library;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@EntityScan("com.Library.services")
@EnableJpaRepositories("com.Library.repositories")
public class LibraryApplication {

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

}

型号:

package com.Library.models.dtos;

import lombok.Getter;
import lombok.Setter;

import javax.persistence.*;

@Getter
@Setter
@Entity
public class BookCategory {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long Id;

    private String Name;

}

存储库:

package com.Library.repositories;

import com.Library.models.dtos.BookCategory;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface BookCategoryRepository extends JpaRepository<BookCategory,Long> {

    List<BookCategory> findAll();
}

服务:

package com.Library.services;

import com.Library.models.dtos.BookCategory;
import com.Library.repositories.BookCategoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class LibraryService {
    @Autowired
    BookCategoryRepository repository;


    public List<BookCategory> getAllCategories() {
        return repository.findAll();
    }
}

控制器:

package com.Library.controllers;

import com.Library.models.dtos.BookCategory;
import com.Library.services.LibraryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@CrossOrigin(origins = "*", allowedHeaders = "*")
@RestController
public class LibraryController{
    @Autowired
    LibraryService libraryService;

    public List<BookCategory> getAllCategories() {
        return libraryService.getAllCategories();
    }

}

可能是什么问题?

这个 bean 定义通常由 Spring Boot Auto-Configuration 自动提供。 spring参考手册explains如何诊断此类问题:

The Spring Boot auto-configuration tries its best to “do the right thing”, but sometimes things fail, and it can be hard to tell why.

There is a really useful ConditionEvaluationReport available in any Spring Boot ApplicationContext. You can see it if you enable DEBUG logging output. If you use the spring-boot-actuator (see the Actuator chapter), there is also a conditions endpoint that renders the report in JSON. Use that endpoint to debug the application and see what features have been added (and which have not been added) by Spring Boot at runtime.

Many more questions can be answered by looking at the source code and the Javadoc. When reading the code, remember the following rules of thumb:

  • Look for classes called *AutoConfiguration and read their sources. Pay special attention to the @Conditional* annotations to find out what features they enable and when. Add --debug to the command line or a System property -Ddebug to get a log on the console of all the auto-configuration decisions that were made in your app. In a running application with actuator enabled, look at the conditions endpoint (/actuator/conditions or the JMX equivalent) for the same information.

在你的例子中,一个简单的全文搜索发现 Hibernate 是 auto-configured by org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,声明如下:

@AutoConfiguration(after = { DataSourceAutoConfiguration.class })
@ConditionalOnClass({ LocalContainerEntityManagerFactoryBean.class, EntityManager.class, SessionImplementor.class })
@EnableConfigurationProperties(JpaProperties.class)
@Import(HibernateJpaConfiguration.class)
public class HibernateJpaAutoConfiguration {

}

正如您从 ConditionalOnClass 注释中看到的那样,仅当您的类路径包含来自 spring-orm-jpa 的 类 LocalContainerEntityManagerFactoryBean、来自 JPA 规范的 EntityManager 时才应用此配置,以及休眠 jar 中的 SessionImplementor

很可能您丢失了这些 JAR 文件之一(maven 依赖项),或者其中一个的版本错误。 ConditionEvaluationReport 应该会告诉您要检查的具体包名。