2013-03-09 69 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); 
    } 
};