我有一个奇怪的问题,Spring 不会尝试将定义的值传递给构造函数参数中的占位符。目前它被定义为 ${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);
}
}
最佳答案
您的加载有缺陷,您应该使用 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 .
关于java - Spring 不会尝试将值注入(inject)到 constructor-arg 占位符中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24281633/