java - 使用spring的@Value注解出错

 不常用的小小号 发布于 2022-10-29 20:54

容器启动的时候出错

配置文件如下:

报错信息如下:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'communityController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private int cn.wanjubang.toy.core.controller.Basecontroller.maxPic; 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: "${maxPic}"

Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private int cn.wanjubang.toy.core.controller.Basecontroller.maxPic; 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: "${maxPic}"

怎么解决呢?

4 个回答
  • int 换成String
    private String maxPic.

    2022-11-12 01:47 回答
  • exception is java.lang.NumberFormatException: For input string: "${maxPic}",你是不是写的maxPic加了引号报错了

    2022-11-12 01:47 回答
  • Failed to convert value of type 'java.lang.String' to required type 'int'; nested exception is java.lang.NumberFormatException: For input string: "${maxPic}"

    这个报错这么明显。。。init bean的时候spring自动转换赋值macPic参数,但是String 转int 异常了

    2022-11-12 01:47 回答
  • 1.这个首先确保下,你的properties位置没有错,如果你是跑单测时候,最好确保在test的路径下也有。

    2.如果确认配置文件是OK的,spring会有一个工具类NumberUtils来处理。

                return (T) (isHexNumber(trimmed) ? Byte.decode(trimmed) : Byte.valueOf(trimmed));
            }
            else if (targetClass.equals(Short.class)) {
                return (T) (isHexNumber(trimmed) ? Short.decode(trimmed) : Short.valueOf(trimmed));
            }
            else if (targetClass.equals(Integer.class)) {
                return (T) (isHexNumber(trimmed) ? Integer.decode(trimmed) : Integer.valueOf(trimmed));
            }

    会把string转换成Intger类型,如果还是不行的话,可以试试用SPEL语句,来强制转换

    "#{T(java.lang.Integer).parseInt('${maxPic}')}"
    2022-11-12 01:47 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有