0

我有一个奇怪的问题,即 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);
  }
}
4

1 回答 1

1

您的加载有缺陷,您应该使用 aApplicationContext而不是 a 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);
  }
}

有关差异,请查看参考指南

于 2014-06-18T10:22:49.577 回答