2

这是我的课:

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
PropertyPlaceholderConfigurer pph = new PropertyPlaceholderConfigurer();
pph.setLocations(new Resource[]{new ClassPathResource("one.properties"), new ClassPathResource("two.properties")});
context.addBeanFactoryPostProcessor(pph);
context.refresh();

Controller obj1 = (Controller) context.getBean("controller");
System.out.println(obj1.getMessage());

Controller2 obj2 = (Controller2) context.getBean("controller2");
System.out.println(obj2.getMessage());
System.out.println(obj2.getInteger());

这是相关的xml配置:

   <bean id="controller" class="com.sample.controller.Controller">
       <property name="message" value="${ONE_MESSAGE}"/>
   </bean>
   <bean id="controller2" class="com.sample.controller.Controller2">
       <property name="message" value="${TWO_MESSAGE}"/>
        <property name="integer" value="${TWO_INTEGER}"/>
   </bean>

一、属性:

ONE_MESSAGE=ONE

二、属性:

TWO_MESSAGE=TWO
TWO_INTEGER=30

TWO_MESSAGE 被正确分配为字符串 TWO。注入 TWO_INTEGER 时出现 NumberFormatException。有没有办法在不添加一个接受 String 并将其转换为 Controller2 类中的 int 的 setter 的情况下实现这一点?

错误 :

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'controller2' defined in class path resource [beans.xml]: Initialization of bean failed; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert property value of type 'java.lang.String' to required type 'int' for property 'integer'; nested exception is java.lang.NumberFormatException: For input string: "${TWO_INTEGER}"

谢谢。

4

1 回答 1

5

可能您的应用程序属于这一行(如果我错了,请提供完整的堆栈跟踪):

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

因为 Spring 无法解析${TWO_INTEGER}(此属性尚未在上下文中加载)。因此,您可以在加载属性后移动上下文初始化:

 ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext();
 PropertyPlaceholderConfigurer pph = new PropertyPlaceholderConfigurer();
 pph.setLocations(new Resource[]{new ClassPathResource("one.properties"), new ClassPathResource("two.properties")});
 context.addBeanFactoryPostProcessor(pph);
 context.setConfigLocation("beans.xml");
 context.refresh();

希望这有帮助。

于 2013-08-02T19:53:40.623 回答