【项目问题解决】 : Failed to convert value of type ‘java.lang.String‘ to required type ‘int‘;

【项目问题解决】 : Failed to convert value of type ‘java.lang.String‘ to required type ‘int‘;_第1张图片

目录

【项目问题解决】: Failed to convert value of type 'java.lang.String' to required type 'int'; nested exception is java.lang.NumberFormatException: For input string: ""

  • 1.问题描述
  • 2.问题原因
  • 3.解决方案
  • 4.其他问题
  • 5.参考


文章所属专区 项目问题解决


1.问题描述

使用@Value注解读取配置,配置整形变量为空

Failed to convert value of type ‘java.lang.String’ to required type ‘int’; nested exception is java.lang.NumberFormatException: For input string: “”

Error creating bean with name ‘singleQueryService’: Unsatisfied dependency expressed through field ‘electronicMaterialService’; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘electronicMaterialService’: Unsatisfied dependency expressed through field ‘outsidePort’; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert value of type ‘java.lang.String’ to required type ‘int’; nested exception is java.lang.NumberFormatException: For input string: “”

2.问题原因

使用@Value注解读取配置,配置整形变量为空,默认取了一个空字符串导致异常

3.解决方案

  1. 检查配置文件:首先,检查你的配置文件,确保outsidePort的配置值存在且为一个有效的整数值。确保没有将配置值设置为空字符串。

  2. 检查字段类型:确认outsidePort字段的类型是int,而不是String。在electronicMaterialService类中,确保outsidePort字段的类型与配置文件中的类型一致。

  3. 使用默认值或可选类型:如果你的配置值可能为空,你可以考虑使用可选类型(如Integer)或设置一个默认值作为备选方案。在electronicMaterialService类中,你可以将outsidePort字段的类型设置为Integer,并在需要使用该字段时进行空值检查。

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class ElectronicMaterialService {
    @Value("${outside.port:0}")
    private Integer outsidePort;

    // Getter and Setter
    
    public Integer getOutsidePort() {
        return outsidePort;
    }

    public void setOutsidePort(Integer outsidePort) {
        this.outsidePort = outsidePort;
    }
}

4.其他问题

在配置中配置了空配置项,而变量是整形,会导致 For input string: " "问题
【项目问题解决】 : Failed to convert value of type ‘java.lang.String‘ to required type ‘int‘;_第2张图片
整形变量配置为配置项,如果没有数据可以直接用:1设置默认值,但是配置文件里对应的配置项不可为空

5.参考

Spring boot @Value 获取值为 null
深度解析@Value注解,你真的彻底了解过吗?
Spring-外部配置的值是如何通过@Value注解获取的?

给个三连吧 谢谢谢谢谢谢了
在这里插入图片描述

你可能感兴趣的:(项目问题解决,java,开发语言,firebug,bug,服务器,c++,c语言)