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

ぐ巨炮叔叔 提交于 2019-12-03 08:17:30

问题


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

@Service
public class MyService {

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

// ...

and using Spring property placeholder (Properties files):

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}"

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


回答1:


Try changing the following line

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

to

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



回答2:


This should solve the problem-

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



回答3:


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.



来源:https://stackoverflow.com/questions/42733067/spring-value-typemismatchexceptionfailed-to-convert-value-of-type-java-lang-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!