这是我的班级:
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.properties:
TWO_MESSAGE=TWO
TWO_INTEGER=30
TWO_MESSAGE被正确分配为字符串TWO。 注入TWO_INTEGER时,我收到NumberFormatException。 有没有办法实现这一点,而无需添加一个带有String的setter并将它转换为Controller2类中的int?
错误:
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}"
感谢。
答案 0 :(得分:4)
可能你的应用程序属于这一行(如果我弄错了,请提供完整的stacketrace):
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();
希望得到这个帮助。