2011-11-30 61 views
5

使用Spring-Context MANIFEST definitions,我試圖執行component-scan來搜索Spring批註的Bean的包。我的Spring XML配置如下所示:OSGi中的Spring組件掃描找不到任何內容

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd 
     http://www.osgi.org/xmlns/blueprint/v1.0.0 http://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd"> 

    <!-- Scans the classpath of this application for @Components to deploy as 
     beans --> 
    <context:component-scan 
     base-package="com.some.other.module.one,com.another.module.two" /> 

    <context:annotation-config /> 
.... 

</beans> 

在MANIFEST中,我使用Spring批註導入了包含類的包。但是,當我檢查ApplicationContext時,它沒有任何註釋的bean。

我相信這是因爲我們正在掃描的類路徑在不同的包中。這些包不直接導入包含Spring註釋的類。令人困惑的是,爲什麼Spring沒有選擇組件掃描從主包開始的類路徑?它看起來好像是在使用每個包的類路徑進行類路徑掃描時。有沒有辦法讓類路徑掃描使用掃描開始的包的類路徑? 。

編輯

由於Danail Nachev下面說,當春天確實類路徑掃描,它發生只有那類路徑是發生在模塊內的解決辦法是使用:

  1. 將每個模塊的配置置於Spring 3 @Configuration bean中。
  2. 在您的頂級捆綁軟件中使用初始化@Configuration bean的XML文件。
  3. 頂級@Configuration bean使用@Import導入其他配置文件。
  4. 請確保您的MANIFEST中有Require-Bundle,以確保您正在導入的配置可用。

回答

7

OSGi的全部都是模塊化的,所以它在捆綁之間有很明顯的分離很重要。如果Spring可以在單個ApplicationContext下將它們聯合起來,將不會比通常的Spring應用程序有所不同,其中一切都在單個類路徑中可用。像這樣的東西。

發生什麼事情是每個bundle都收到它自己的ApplicationContext。這些ApplicationContexts可以使用OSGi Service Registry交換bean。您需要將bean標記爲導出並將其導入其他ApplicationContexts中,否則它們彼此不可見。

這應該解釋爲什麼你不能用單個Spring上下文來配置所有東西,並且期望從一個bundle開始並找到所有的bean。 Spring上下文僅掃描單個bundle,並可選擇將bean導入/導出爲OSGi服務。

從這裏解釋型:Chapter 8. Packaging and Deploying Spring-based OSGi applications

+0

謝謝你,這正是觀察到的行爲。我設法找到了一個解決方法,而不使用類路徑掃描。 –