【问题标题】:SpringBoot scanBasePackages does not find repository in different jarSpringBoot scanBasePackages 在不同的 jar 中找不到存储库
【发布时间】:2018-11-15 00:05:29
【问题描述】:

我有一个这样的 Spring Boot 应用程序:

package my.package;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jms.activemq.ActiveMQAutoConfiguration;
import org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration;

@SpringBootApplication
public class MySpringBootApp{

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

}

我在包里有个服务my.package.service

@Service
public class MyService {

private ServiceInADifferentJar  dep;

public MySerivce(ServiceInADifferentJar dep) {
this.dep = dep;
}

}

ServiceInADifferentJar 类是不同 JAR 中的 @Service 注释类,我将其作为 maven 依赖项包含在内。

JAR 文件结构如下:

src/main/java
- some.package.repository
    MyRepository.java
- some.package.service
    ServiceInADifferentJar.java

MyRepository 是一个 @Repository 注释接口,它扩展了 Spring Data 接口。

ServiceInADifferentJar 在其构造函数中注入MyRepository

当我启动应用程序时,我收到一个错误,即找不到ServiceInADifferentJar

然后我将它添加到我的 SpringBootApp 中

@SpringBootApplication(scanBasePackages = {"some.package"})

找到了ServiceInADifferentJar,但没有找到MyRepository

为什么不呢?为什么其他 JAR 中 some.package 的所有子包都没有被扫描到?

* 编辑 *

存储库

package some.package.repository;

    @Repository
    public interface MyRepository extends MongoRepository<SomeEntity, String> {

    }

【问题讨论】:

  • 你能添加你的存储库接口吗?
  • @Berger 我编辑了我的问题
  • 你在用 Maven 构建吗?
  • @TheHeadRush 是的,两者都是 maven 项目。

标签: java spring-boot


【解决方案1】:

您可能希望使用 EnableMongoRepositories 注释,以便找到您的 Mongo 存储库。

@EnableMongoRepositories(basePackages = "some.package.repository")

以下问题尽管是关于 JPA 存储库的,但对存储库扫描的工作方式有更多解释:

Can't Autowire @Repository annotated interface in Spring Boot

【讨论】:

  • 谢谢,就是这样!我有点惊讶 Spring 实际上需要这些指向这些包的显式指针,但是,至少它现在可以工作了。再次感谢!
【解决方案2】:

嘿,你应该把它放在你的主类中 @SpringBootApplication 标签之后 @ComponentScan(basePackages = {"some.package"})

【讨论】:

  • 我这样做了,但它仍然找不到存储库。
猜你喜欢
  • 1970-01-01
  • 2016-06-23
  • 1970-01-01
  • 2015-05-19
  • 1970-01-01
  • 1970-01-01
  • 2010-11-24
  • 1970-01-01
  • 2020-09-12
相关资源
最近更新 更多