在 Spring Boot 中将存储库自动连接到库项目

问题描述 投票:0回答:2

我正在开发一个 Spring Boot 多模块项目。我创建了单独的模块,如下

  • com.foodshop.api
    -(这是一个 Spring Boot 项目,起点,并且
    com.foodshop.application
    com.foodshop.persistence
    都在此处添加为依赖项)
  • com.foodshop.application
    -(我有业务逻辑的应用程序层,这是一个库项目,
    spring-boot-starter
    com.foodshop.persistence
    在此处添加为依赖项)
  • com.foodshop.persistence
    -(这是定义存储库的位置,
    spring-boot-starter-data-mongodb
    作为依赖项添加到此项目中)

上面提到的所有 3 个项目都包装在父项目

pom
maven 项目中,父项目
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.foodshop</groupId>
    <artifactId>foodshop-backend</artifactId>
    <version>0.0.1</version>
    <packaging>pom</packaging>

    <properties>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>

    <modules>
        <module>foodshop.persistence</module>
        <module>foodshop.application</module>
        <module>foodshop.api</module>
    </modules>
</project>

项目构建没有任何错误。

foodshop.api
的应用程序类我注释如下,以便它可以看到其他模块中的依赖关系

@SpringBootApplication(scanBasePackages = {"com.foodshop"})

但是当我尝试运行 API 项目时,看起来

foodshop.application
无法找到并自动装配
foodshop.persistence

中定义的存储库

我收到如下错误;

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

Description:

Parameter 0 of constructor in com.foodshop.application.MealManager required a bean of type 'com.foodshop.persistence.repository.MealRepository' 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.foodshop.persistence.repository.MealRepository' in your configuration.

我已经用

MealRepository
注释正确注释了
@Repository
,但我觉得我错过了一些重要的东西。

如果我能在这个问题上获得一些帮助,我将不胜感激。

spring spring-boot spring-data spring-mongodb spring-modules
2个回答
2
投票

经过 20 多个小时的阅读并遵循反复试验的方法,我终于找到了问题所在。根据Spring官方文档

如果您的应用程序还使用 JPA 或 Spring Data,则 @EntityScan 和 @EnableJpaRepositories(和相关)注释仅继承它们的 未明确指定时来自 @SpringBootApplication 的基础包 指定的。也就是说,一旦您指定 scanBasePackageClasses 或 scanBasePackages,您可能还必须显式使用 @EntityScan 和 @EnableJpaRepositories 及其包扫描 明确配置。

由于我使用

spring-boot-starter-data-mongodb
,我将我的Application类注释如下;

@SpringBootApplication(scanBasePackages = {"com.foodshop"})
@EnableMongoRepositories(basePackages = "com.foodshop.persistence")
public class Application {
  // main method goes here.
}

@EnableMongoRepositories
注释成功了。


0
投票

这个答案也适用于使用@EnableJpaRepositories(“com.dao.package”)的JPA

© www.soinside.com 2019 - 2024. All rights reserved.