首页 > 解决方案 > 无法将外部 Jar 中的存储库自动装配到 Spring Boot 应用程序中

问题描述

我已将应用程序的整个实体和存储库接口打包到一个 jar 中。存储库是使用 @Repository 注释编写的:

@Repository
public interface InternalUserRepository extends JpaRepository<InternalUser, Long>{

}

我已将这个 jar 文件包含在我的 Spring Boot 应用程序中,并尝试从控制器自动连接这样的接口:

@RestController
public class AuthenticationController {

    @Autowired
    AuthenticationService authenticationService;

    @Autowired
    InternalUserRepository internalUserRepository;


    @GetMapping("/")
    public String home() {
        return "Hello World!";
    }

}

我的主应用程序类的编写如下:

@SpringBootApplication
@EnableJpaRepositories
@ComponentScan("com.cdac.dao.cdacdao.*")
public class CdacAuthenticationMgntApplication {

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

存储库没有自动装配。当我启动 Spring boor 应用程序时,出现以下错误:

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

Description:

Field internalUserRepository in 
com.cdac.user.cdacauthenticationmgnt.controller.AuthenticationController required a bean of type 'com.cdac.dao.cdacdao.repository.InternalUserRepository' that could not be found.


Action:

Consider defining a bean of type 'com.cdac.dao.cdacdao.repository.InternalUserRepository' in your configuration.

有没有人尝试过类似的架构?

标签: javaspringspring-bootjpaspring-data-jpa

解决方案


如果您的 JPA 存储库与 Spring Boot 应用程序类位于不同的包中,则必须在EnableJpaRepositories注释上指定该包,而不是Component

@EnableJpaRepositories("com.cdac.dao.cdacdao")

您指定的包ComponentScan用于将类检测为常规 Spring bean,而不是存储库接口。


推荐阅读