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

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

@Service
public class MyService {

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

// ...

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

item.priceFactor=0.1

我得到例外:

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

有没有办法使用来自属性文件的双精度值?


答案 1

尝试更改以下行

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

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

答案 2

这应该可以解决问题——

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

推荐