【发布时间】:2013-08-04 03:42:36
【问题描述】:
这是我的课:
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.properties:
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}"
谢谢。
【问题讨论】:
-
PropertyPlaceholderConfigurer显然没有找到属性文件,或者属性文件不包含像${TWO_INTEGER}这样的任何属性。你检查过这个吗? -
我检查了这个。事实上,同一文件中的其他 String 属性已正确分配。 one.properties 具有:
ONE_MESSAGE=ONE和 two.properties 具有:TWO_MESSAGE=TWO TWO_INTEGER=30并且“TWO_MESSAGE”属性被正确读取。只是,澄清一下。 two.properties 中有两行,而不是此处显示一行的格式。谢谢。 -
您可以编辑您的问题并添加此相关信息。它将更好地格式化为评论。
-
为什么不能在xml文件中定义PropertyPlaceholderConfigurer?
-
LaurentG :编辑了问题。 @bellabax:属性文件名是在运行时决定的。除非有办法在 xml 文件中定义它然后以编程方式更改它,否则我必须这样做。谢谢。
标签: spring setter numberformatexception