2017-02-15 218 views
1

我正在創建一個使用spring 4.3.0的庫。一個spring-boot應用程序將使用此庫。目前,我在Spring-Boot應用程序的主類中使用@ComponentScan來掃描庫中的Bean,而不是我想自動配置它。所以我做的是我在庫中創建了一個配置類,並在配置中聲明瞭@ComponentScan文件。創建自動配置彈簧庫以彈簧啓動應用程序

消費春季啓動應用程序的庫後它不掃描庫內的豆類和罰球,

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.sample.book.client.service.BookService] found for dependency [com.sample.book.client.service.BookService]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} 
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1406) 
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1057) 
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1019) 
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:566) 
... 33 common frames omitted 

如何解決這個問題?爲什麼Spring在@Configuration之前掃描@service類?

您的幫助應該是可觀的,如果需要,我會提供代碼示例。

回答

1

我猜你的配置沒有從你的啓動應用程序默認加載。 我也猜你還沒有加入

@EnableAutoConfiguration 

到你的啓動應用程序。

因此,您可以嘗試將您的配置添加到Annotation @EnableAutoConfiguration以便由應用程序加載。然後,您在庫-JAR中放入META-INF/spring.factories的配置會自動加載。

或者你可以在你的@SpringBootApplication@Import配置

+0

我的春天啓動的應用程序已經與@SpringBootApplication所以再次宣稱SpringBootApplication將redundant.Also已指定「META-INF/spring.factories」註明,我的庫是用彈簧不是春,那麼啓動我如何使用以下導入「org.springframework.boot.autoconfigure.EnableAutoConfiguration」指定自動配置? 「EnableAutoConfiguration」由spring-boot提供,不是spring請糾正我,如果我錯了 – VelNaga

+1

當你的應用程序是allready a @ SpringBootApplication時,你有AutoConfiguration啓用。然後,您可以在庫JAR中放置META-INF/spring-factories,或者您可以@導入您的庫的配置 –

+0

它可以工作。謝謝。我跟着META-INF/spring.factories「的方法,它的工作方式就像一個魅力,但是你能定義@Import還是可以請你分享一個關於」@Import「的鏈接? – VelNaga

2

這在我看來,最可能的原因是你的庫駐留在不同的包比你的春天啓動的應用程序(和它的子包)。使用@SpringBootApplication註釋類時,您還會將@ComponentScan註釋設置爲默認值(即掃描包中給定類所在的組件)。

個人而言,我更喜歡在我的圖書館項目中創建一個@Configuration註釋類。這樣的類負責正確的庫設置(聲明組件掃描等)。後來,在依賴項目中,我使用@Import註釋來導入該配置類(以及相應的bean)。