Spring @Value TypeMismatchException:无法将“java.lang.String”类型的值转换为所需类型“java.lang.Double”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42733067/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 00:20:34  来源:igfitidea点击:

Spring @Value TypeMismatchException:Failed to convert value of type 'java.lang.String' to required type 'java.lang.Double'

javaspringspring-elspring-propertiesproperty-placeholder

提问by guilhebl

I want to use the @Value annotation to inject a Double property such as:

我想使用 @Value 注释来注入一个 Double 属性,例如:

@Service
public class MyService {

    @Value("${item.priceFactor}")
    private Double priceFactor = 0.1;

// ...

and using Spring property placeholder (Properties files):

并使用 Spring 属性占位符(属性文件):

item.priceFactor=0.1

I get Exception:

我得到异常:

org.springframework.beans.TypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.lang.Double'; nested exception is java.lang.NumberFormatException: For input string: "${item.priceFactor}"

org.springframework.beans.TypeMismatchException:无法将“java.lang.String”类型的值转换为所需类型“java.lang.Double”;嵌套异常是 java.lang.NumberFormatException:对于输入字符串:“${item.priceFactor}”

Is there a way to use a Double value coming from a properties file?

有没有办法使用来自属性文件的 Double 值?

采纳答案by bcr666

Try changing the following line

尝试更改以下行

@Value("${item.priceFactor}")

to

@Value("#{new Double('${item.priceFactor}')}")

回答by Vitali Pom

How about storing a String and converting to numbers like integers and doubles through getters and setters? For safe code with Java injection you should always use getters and setters and only for other methods in any case. I advice you warmly to read about java security (Which is NOT for hackers), but more for code usage and writing likewise the one you uploaded, wich uses injection.

如何存储字符串并通过 getter 和 setter 转换为整数和双精度数?对于 Java 注入的安全代码,您应该始终使用 getter 和 setter,并且在任何情况下都只用于其他方法。我强烈建议您阅读有关 Java 安全性的内容(这不是针对黑客的),但更多的是用于代码使用和编写您上传的代码,其中使用了注入。

回答by pkoli

This should solve the problem-

这应该可以解决问题-

@Value("#{T(Double).parseDouble('${item.priceFactor}')}")
private Double priceFactor;