问题
I am using sprin version 4.3.8.RELEASE. also i am using @Value
to inject values from property file, if the properties are string that no problem, but if the property is Integer
that is a problem (i know there is many questions about this i tried all the answers but the issue still exist)
The property is
CONNECTION.TIME.OUT=100000
First solution
@Value("${CONNECTION.TIME.OUT}")
protected Integer connectionTimeOut;
Ecxeption
Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'; nested exception is java.lang.NumberFormatException: For input string: "${CONNECTION.TIME.OUT}"
Second solution
@Value("#{new Integer('${CONNECTION.TIME.OUT}')}")
protected Integer connectionTimeOut;
Exception
EL1003E: A problem occurred whilst attempting to construct an object of type 'Integer' using arguments '(java.lang.String)'
Third solution
@Value("#{new Integer.parseInteger('${CONNECTION.TIME.OUT}')}")
protected Integer connectionTimeOut;
Exception
EL1003E: A problem occurred whilst attempting to construct an object of type 'Integer' using arguments '(java.lang.String)'
any ideas why is that
回答1:
For @Value("${CONNECTION.TIME.OUT}")
your error is java.lang.NumberFormatException: For input string: "${CONNECTION.TIME.OUT}"
. This means that expression was not processed resulting in Integer.parseInt("${CONNECTION.TIME.OUT}")
which thrown the NumberFormatException
.
Either there is no PropertyPlaceholderConfigurer
bean registered in the Spring context and @Value
annotations are not processed or there is no property CONNECTION.TIME.OUT
defined.
回答2:
To avoid such type of situation where the exception occurs due to un-availibilty of the property, Add default value in the tag. If property is not available then it will populate the default value
@Value("${CONNECTION.TIME.OUT:10}")
回答3:
Your property file is probably not loaded properly.
When provided with no valid value for a property placeholder, Spring will automatically try to assign this value to the name of the @Value
annotation. In your case, this:
@Value("#{new Integer('${CONNECTION.TIME.OUT}')}")
protected Integer connectionTimeOut;
Is interpreted as:
protected Integer connectionTimeOut = new Integer("${CONNECTION.TIME.OUT}");
Which, indeed, brings an error.
Try to either configure a PropertyPlaceholderConfigurer
in your beans, or make sure that your property file is loaded properly in your classpath by your configuration. Something among the lines of:
<context:property-placeholder
ignore-unresolvable="true"
location="classpath:yourfile.properties" />
In your configuration file will help, in this case.
来源:https://stackoverflow.com/questions/49793547/spring-value-always-gives-an-error-if-property-is-integer