簡體   English   中英

無法在 spring boot 應用程序中自動裝配接口

[英]Cannot Autowire interface in spring boot app

我正在使用 spring boot 開發 REST API。 以下是我的包結構 當我嘗試啟動我的應用程序時出現以下異常

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

Description:

Field articleRepository in com.abc.service.ArticleService required a bean of type 'com.abc.dao.ArticleRepository' that could not be found.


Action:

Consider defining a bean of type 'com.abc.dao.ArticleRepository' in your configuration.

以下是我的項目結構-

com.abc
com.abc.bean
    -Article.java
com.abc.controller
    -ArticleController.java
com.abc.dao
    -ArticleRepository.java (Interface)
com.abc.service
    -ArticleService.java
com.abc.web
    -AbcApplication.java (main Springboot class)

在 AbcApplication.java 因為它不在根包中,所以我有以下注釋

@SpringBootApplication
@ComponentScan(basePackages="com.abc.*")

我嘗試了幾種方法 -

  • 我將 AbcApplication.java 移動到根包 com.abc 但沒有成功
  • 而不是接口(ArticleRepository.java)我把它變成了一個類,它正在工作
  • 我將它保留為接口,但將注釋從 @Repository 更改為 @Service/Component 仍然沒有成功。

如果我將它更改為類而不是接口,我很困惑它是如何工作的。

@Repository
public interface ArticleRepository {

}

您沒有任何用於 ArticleRepository 的 bean。 如果您將使用 Spring Data Jpa,則必須擴展一種存儲庫: https ://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories。

如果您將使用自己的存儲庫,則必須實現它。

如果您使用任何 RDBMS 並且ArticleRepository存儲庫負責與您的數據庫交互,那么您需要在ArticleRepository中擴展CrudRepositoryJpaRepository ,那么只有 Spring 才能創建ArticleRepository的 bean,並且您將能夠自動裝配您的存儲庫。

如果您沒有擴展任何CrudRepositoryJpaRepository ,那么在創建 bean 時, ArticleRepository只是普通的 java 接口,普通接口不能被實例化。

至於你的問題:

Instead of interface(ArticleRepository.java) I made it a class, it is working

這是因為當您將其聲明為一個類時,Spring 會實例化一個具體類,因此將在創建 bean 時創建實際對象,並且一切都將按應有的方式運行。

理想情況下,您應該有一個實現接口 ArticleRepository 的類。 用@Repository 注釋該類,spring 將負責接線。

我也遇到了同樣的問題。 我錯過的是spring-boot-starter-jpa依賴項。 當我在 pom.xml 文件中添加此依賴項時,它起作用了。

MyBatis 為您提供了兩個使用 spring boot 訪問數據庫的示例。@Component 或@Mapper。

示例鏈接: mybatis-spring-boot-sample-xml

建議:完整顯示您的ArticleRepository代碼。

接口不需要任何注解(@repository 和@Service 都不需要)。

如果它是一個 DAO 文件,請在實現相應接口的類中添加 @Repository 注解。

並且,如果它是一項服務,則將@Service 注釋添加到實現相應接口的類中。

暫無
暫無

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

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