Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring @Value always gives an error if property is Integer

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

like image 767
Melad Basilius Avatar asked Apr 12 '18 09:04

Melad Basilius


People also ask

What does @value do in spring?

Spring @Value annotation is used to assign default values to variables and method arguments. We can read spring environment variables as well as system variables using @Value annotation.

What does @value mean in Java?

@Value is a Java annotation that is used at the field or method/constructor parameter level and it indicates a default value for the affected argument. It is commonly used for injecting values into configuration variables - which we will show and explain in the next part of the article.

How property values can be injected directly into your beans in spring boot?

Property values can be injected directly into your beans using the @Value annotation, accessed via Spring's Environment abstraction or bound to structured objects via @ConfigurationProperties . Spring Boot uses a very particular PropertySource order that is designed to allow sensible overriding of values.

How do you inject Spring values?

You can do this in Spring 3 using EL support. Example: @Value("#{systemProperties. databaseName}") public void setDatabaseName(String dbName) { ... }


1 Answers

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}")
like image 124
Dhruv Raj Singh Avatar answered Sep 18 '22 11:09

Dhruv Raj Singh