gpt4 book ai didi

spring - 注入(inject) int 属性时出现 NumberFormatException

转载 作者:行者123 更新时间:2023-12-02 04:55:47 25 4
gpt4 key购买 nike

这是我的课:

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>

一个.properties:

ONE_MESSAGE=ONE

两个属性:

TWO_MESSAGE=TWO
TWO_INTEGER=30

TWO_MESSAGE 被正确分配为字符串二。注入(inject) 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}"

谢谢。

最佳答案

可能您的应用程序属于这一行(如果我弄错了,请提供完整的 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();

希望这对您有所帮助。

关于spring - 注入(inject) int 属性时出现 NumberFormatException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18024186/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com