2013-04-08 58 views
1

我很新的春天是好的;)引導@Configuration

我有一個共享的模塊,我會打電話給「核心」和一對夫婦的項目,這取決於核心。這些子項目有spring/app-context.xml文件,並且在它們被執行的環境中,spring被另一個框架初始化。

在「核心」的項目,我想使用定義一些單身人士服務的@Configuration方法:然後

@Configuration 
public class AppConfig 
{ 
    @Bean 
    public MyService myService() 
    { 
     return new MyServiceImpl(); 
    } 
} 

核心封裝在一個罐子,包括在分項目的類路徑。

如何引導核心模塊的服務,使它們可用於子項目中的@Autowire?

編輯:

我遇到的錯誤是:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [package.MyService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

我已經試過以下每個(完全)的:

<context:component-scan base-package="package" /> 
<import resource="classpath*:spring/core-context.xml" /><!-- defined in core.jar with MyService as a bean --> 
<bean class="package.AppConfig" /> 

但只添加這子項目的app-context.xml似乎解決了錯誤:

<bean id="MyService" class="package.MyServiceImpl" /> 
+0

...或者我並不完全依賴於使用@Configuration方法,但是我必須能夠在覈心模塊中配置beans/services,而不必在子項目中重新配置它們 – pstanton 2013-04-08 03:02:29

+0

您是否採取了看看log4j日誌?在DEBUG級別日誌記錄中,您應該能夠看到更多關於爲什麼找到「AppConfig」而不是「MyService」的信息。 – 2013-04-08 04:08:27

+0

嗨尼古拉斯,謝謝你的提示。打開彈簧日誌,我可以看到平臺在我的AppConfig上拋出了一個ClassNotFound,這意味着在初始化Spring應用程序上下文之前,容器尚未加載模塊的完整類路徑。我將不得不接受平臺的供應商。 – pstanton 2013-04-08 09:51:49

回答

1

如果你看一看的JavaDoc,它說明了一切:

Via Spring XML

As an alternative to registering @Configuration classes directly against an AnnotationConfigApplicationContext, @Configuration classes may be declared as normal definitions within Spring XML files:

<beans> 
    <context:annotation-config/> 
    <bean class="com.acme.AppConfig"/> 
</beans> 

聽起來好像只是包括@Configuration類作爲一個bean到你的XML配置將它撿起來。

除此之外,您還應該能夠通過component-scan獲取課程,因爲@Configuration的元註釋爲@Component

+0

感謝您的幫助,但我已經嘗試了這兩種方法。請參閱編輯。 – pstanton 2013-04-08 03:58:57

+0

那麼,這是直接從文檔,所以我認爲它應該工作。那麼它不起作用呢?你有例外嗎?你的類路徑設置是否正確?另外,我沒有看到編輯。 – 2013-04-08 04:02:11

+0

正在編輯,thx。 – pstanton 2013-04-08 04:03:32

相關問題