[英]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.