假设我有以下Spring配置( Spring的版本是3.0.3):
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="theFactoryBean" class="wax.MyFactoryBean"/>
<bean id="factoryBeanUser" class="wax.FactoryBeanUser">
<!-- what should be placed here?-->
</bean>
</beans>
我有FactoryBean
实现的实例和一些其他实例。我需要Spring来注入其他实例FactoryBean
,而不是它产生的对象。
有两种可能的方法来解决它。
第一个是显而易见且功能不正常的:
<bean id="factoryBeanUser" class="wax.FactoryBeanUser">
<property name="myFactoryBean" ref="&theFactoryBean"/>
</bean>
使用此配置,Spring在启动时抛出以下异常:
[skipped irrelevant part]
Caused by: org.xml.sax.SAXParseException: The reference to entity "theFactoryBean" must end with the ';' delimiter.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:195)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.fatalError(ErrorHandlerWrapper.java:174)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:388)
at com.sun.org.apache.xerces.internal.impl.XMLScanner.reportFatalError(XMLScanner.java:1414)
我找到了这个解决方案Spring: Getting FactoryBean object instead of FactoryBean.getObject(),这个问题是按答案提出的,有四个人投票赞成。因此,我假设这个解决方案可能会起作用,但目前我的代码中存在错误。
第二个,工作但很笨拙:
public class FactoryBeanUser implements ApplicationContextAware{
private MyFactoryBean myFactoryBean;
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
myFactoryBean = (MyFactoryBean)applicationContext.getBean("&theFactoryBean");
}
}
我的问题是,有没有可能让第一种方法起作用,或者我应该坚持第二种方法?
发布于 2010-08-09 23:24:43
XML解析器似乎将与号(&)解释为XML实体的开始。您可以尝试使用ref="&theFactoryBean"
。
spring docs不清楚这种语法是允许在xml文件中使用,还是仅用于编程查找。但是由于应用程序上下文使用了xml配置,所以我假设&
应该可以工作(尽管它似乎不是特殊符号的最佳选择)。
这就是为什么我会建议另一件事-如果你真的需要工厂bean而不是它的产品,创建另一个不实现FactoryBean
的bean,定义一个方法createObject()
或类似的东西,并在所有需要它的工厂中使用它。
附注-更好地引用包含版本的xsd:
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
https://stackoverflow.com/questions/3441438
复制相似问题