2017-01-02 95 views
3

我有兩個Maven模塊。 第一個,所謂的「應用程序」,包含了只包含這些行的應用類:在Spring Boot應用程序中掃描不同Maven模塊/ JAR的組件

package org.example.application; 

@SpringBootApplication 
@ComponentScan({"org.example.model", "org.example"}) 
public class Application { 
    public static void main(String[] args) { 
     ApplicationContext ctx = SpringApplication.run(Application.class, args); 
    } 
} 

同樣的Maven模塊和封裝,org.example.application,我有一個使用Component一個RestController,反過來用途下面描述的另一個Maven模塊的組件。

另一個名爲「model」的Maven模塊包含組件(crud-存儲庫,實體等)。所有這些類是相同的封裝結構與第一Maven的模塊(org.example)下但在該子包中,像org.example.model.entitiesorg.example.model.repositories

因此,流程是這樣的:

Maven的模塊application在包org.example
SpringBootApplication -> RestController -> MyComponent

,並應在MyComponent被裝配的元件都在model Maven的模塊聯合國的那些包org.example.model

但是當我啓動應用程序我剛剛得到的錯誤:

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

Description: 

Field myRepository in org.example.MyComponent required a bean of type 'org.example.model.repositories.MyRepository' that could not be found. 

Action: 

Consider defining a bean of type 'org.example.model.repositories.MyRepository' in your configuration. 

org.example.model.repositories.MyRepository確實存在的Maven模塊「模型」,但不能由SpringBootApplication類中找到!

正如您所看到的,我試圖將掃描組件明確定義爲: @ComponentScan({"org.example.model", "org.example"})但這似乎沒有幫助。

那麼我做錯了什麼?

回答

6

我不確定這是您的問題,但您爲什麼聲明@ComponentScan,而@SpringBootApplication的目標之一是要掃描的組件的配置。
Spring documentation

The @SpringBootApplication annotation is equivalent to using @Configuration, @EnableAutoConfiguration and @ComponentScan with their default attributes

只是一個猜測:也許是@ComponentScan聲明覆蓋其中@SpringBootApplication你不聲明合適的包掃描一個。

除了包org.example應該足夠,因爲org.example.model是它的孩子。因此,您應該刪除要掃描的軟件包列表中的org.example

試一下:

@SpringBootApplication(scanBasePackages={"org.example"}) 
+0

我都試過,太多,但我得到了同樣的錯誤。所以我認爲組件掃描是在相同的JAR/Maven模塊中的*和*中創建的。我想讓SpringBootApplication掃描相同包中的組件*,但是掃描另一個* JAR/maven模塊中的組件。 – Rox

+0

組件掃描在運行時執行。無論該類是否駐留,如果它位於類路徑中,它應該可以工作。你能發佈項目的pom.xml嗎? – davidxxx

+0

啊,我現在找到了一個解決方案。在上面的文章中,我已經混淆了代碼,而'SpringBootApplication'類實際上駐留在'org.example.application'包中。如果我將'SpringBootApplication'移動到'org.example'包,那麼它就可以工作。但我仍然不明白爲什麼它不能在'org.example.application'下,當我明確地使組件掃描來掃描'org.example'下的所有東西時,比如'@ComponentScan({「org.example.model」, 「org.example」})'。 – Rox

相關問題