这是我的课:
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}"
谢谢。