2013-03-09 31 views
0

全部!Spring IOC GenericXmlApplicationContext不起作用組件掃描

我有這樣的片段:

SomeCustomClassLoader customClassLoader = new SomeCustomClassLoader(); 
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext(); 
ctx.setClassLoader(customClassLoader); 
ctx.load(new ByteArrayResource(bytesData)); 
ctx.refresh(); 
Object testService = ctx.getBean("testService"); 

當我試圖創建一個自定義類加載新的應用程序上下文。上下文文件看起來像:

<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.1.xsd 
      http://www.springframework.org/schema/context 
      http://www.springframework.org/schema/context/spring-context-3.1.xsd 
      "> 

    <context:annotation-config /> 

    <context:component-scan base-package="some.base.package" /> 

    <bean name="testService" class="some.base.package.TestService"/> 
</beans> 

問:爲什麼我能得到TestService的,只要它在上下文中的文件明確聲明,如果這個服務有沒有創造它@Service註解。如何啓用組件掃描。我的代碼有什麼問題?

謝謝。

+0

見這裏的一個例子: http://javagc.blogspot.de/2013/03/providing-gwt-rpc-ser副和other.html – user1050755 2013-03-09 16:41:31

+0

對不起沒有得到它。哪個例子? – 2013-03-09 17:43:02

+0

這是最後一個代碼片段(但它們實際上都只是一個應用程序):-) – user1050755 2013-03-09 19:47:20

回答

0

我覺得問題就在這裏https://jira.springsource.org/browse/SPR-3815

調試彈簧芯可能看起來像後的解決方案:

如果我們看到到類GenericXmlApplicationContext,我們會看到,是有場(XML閱讀器)

private final XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this); 

將其稱之爲思想請求的調用鏈BeanDefinitionRegistry

將要求在掃描期間獲取資源克的類的過程,其中的參數將是這樣的一種:類路徑*:一些/包/名稱/ **/*類

org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider#findCandidateComponents

這意味着GenericXmlApplicationContext可能重寫負責此方法:

GenericXmlApplicationContext ctx = new GenericXmlApplicationContext() { 
    @Override 
    public Resource[] getResources(String locationPattern) throws IOException { 
     if(locationPattern.endsWith(".class")) { 
      List<byte[]> classes = customClassLoader.getAllClasses(); 
      Resource[] resources = new Resource[classes.size()]; 
      for (int i = 0; i < classes.size(); i++) { 
       resources[i] = new ByteArrayResource(classes.get(i)); 
      } 
      return resources; 
     } 

     return super.getResources(locationPattern); 
    } 
};