sha*_*rma 2 setter spring numberformatexception
这是我的课:
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());
Run Code Online (Sandbox Code Playgroud)
这是相关的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>
Run Code Online (Sandbox Code Playgroud)
one.properties:
ONE_MESSAGE=ONE
Run Code Online (Sandbox Code Playgroud)
two.properties:
TWO_MESSAGE=TWO
TWO_INTEGER=30
Run Code Online (Sandbox Code Playgroud)
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}"
Run Code Online (Sandbox Code Playgroud)
谢谢。
可能您的应用程序属于这一行(如果我输入错误,请提供完整的stacketrace):
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Run Code Online (Sandbox Code Playgroud)
因为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();
Run Code Online (Sandbox Code Playgroud)
希望能有所帮助。
| 归档时间: |
|
| 查看次数: |
7295 次 |
| 最近记录: |