0

全部!

我有这个片段:

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注释它没有被创建。如何启用组件扫描。我的代码有什么问题?

谢谢。

4

1 回答 1

0

我认为问题出在https://jira.springsource.org/browse/SPR-3815

调试 Spring Core 后的解决方案可能如下所示:

如果我们查看GenericXmlApplicationContext类,我们将看到它具有字段(xml 阅读器)

private final XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this);

这将被称为请求BeanDefinitionRegistry的调用链

在扫描类进程期间将要求获取资源,其中参数将如下所示:classpath*:some/package/name/**/*.class

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);
    }
};
于 2013-03-10T10:00:11.470 回答