簡體   English   中英

無法將存儲庫從外部 Jar 自動裝配到 Spring Boot App

[英]Can't autowire repository from an external Jar into Spring Boot App

我已將應用程序的整個實體和存儲庫接口打包到一個 jar 中。 存儲庫是用@Repository 注釋編寫的:

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

}

我已經將這個 jar 文件包含在我的 spring 啟動應用程序中,並嘗試從控制器自動連接這樣的接口:

@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.

有沒有人嘗試過類似的架構?

如果您的 JPA 存儲庫與 Spring Boot 應用程序類位於不同的包中,則必須在EnableJpaRepositories注釋上指定該包,而不是Component

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

您在ComponentScan上指定的包用於將類檢測為常規 Spring bean,而不是存儲庫接口。

我記得,@ComponentScan 應該采取一個包的完整路徑,所以我認為你的package.*不起作用。

嘗試改用類型安全的組件掃描:

// You refer to your packages of your base project and your module here. 
// Choose the class so that their package is cover all child package
@SpringBootApplication(scanBasePackageClasses = {xxx. InternalUserRepository.class, xxx.CdacAuthenticationMgntApplication.class}) 

@EnableJpaRepositories
// No need to explicit @ComponentScan
public class CdacAuthenticationMgntApplication {

或者你可以試試@EnableJpaRepositories("com.cdac.dao.cdacdao")

無論哪種方式,您都應該選擇最外層包中的類(Spring 也會嘗試在這些組件掃描包的子包中查找 bean)

注解@SpringBootApplication 已經支持所有功能所以我們不需要手動配置

@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
        @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
        @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM