我有这个奇怪的问题,Spring没有尝试将定义的值传递给构造函数arg中的占位符。目前它被定义为${myProperty}
,但我可以在那里写任何东西,没有错误。它只是将文字字符串${myProperty}
传递给bean构造函数,否则配置似乎完美无缺。
我的beans.xml看起来像:
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder order="1" properties-ref="propertiesBean" />
<bean id="propertiesBean" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="properties">
<props>
<prop key="myProperty">Foo</prop>
</props>
</property>
</bean>
<bean id="wrapperBean" class="springapp.bean.Wrapper">
<constructor-arg value="${myProperty}">
</constructor-arg>
</bean>
</beans>
有没有人知道我在这个配置中缺少什么。也许它是显而易见的,我对Spring没有多少经验。使用Spring版本3.2.x和WildFly 8.1作为容器。
编辑:
beans.xml的加载方式如下:
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Log log = LogFactory.getLog(TestServlet.class);
private XmlBeanFactory factory;
public void init() throws ServletException {
ClassPathResource resource = new ClassPathResource("beans.xml", TestServlet.class.getClassLoader());
factory = new XmlBeanFactory(resource);
}
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Wrapper bean = (Wrapper) factory.getBean("wrapperBean");
String value = bean.inner.value;
resp.getWriter().print(value);
}
}
答案 0 :(得分:1)
您的加载存在缺陷,您应该使用ApplicationContext
而不是BeanFactory
。
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Log log = LogFactory.getLog(TestServlet.class);
private ApplicationContext ctx;
public void init() throws ServletException {
ctx = new ClassPathXmlApplicationContext("beans.xml");
}
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Wrapper bean = ctx.getBean("wrapperBean", Wrapper.class);
String value = bean.inner.value;
resp.getWriter().print(value);
}
}
对于差异检查the reference guide。