[英]Spring IOC GenericXmlApplicationContext does not work component scanning
所有!
我有这个片段:
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注释,则不会创建它。 如何启用组件扫描。 我的代码有什么问题?
谢谢。
我认为问题出在这里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);
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.