4

I have application.properties file and I successfully get String values from it with @Value. I am having problems getting an int from it.

jedisHostName=127.0.0.1
redisPort=6379

In my config class I have

@Value("${jedisHostName}")
private String hostName;

and it works fine, but when I try to

@Value("#{new Integer.parseInt('${redisPort}')}")
private Integer redisPort;

I get

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'secret***': Unsatisfied dependency expressed through field 'redisPort';

I am also trying only

@Value("#{new Integer('${redisPort}')}")

but I get same exception. I am even trying to simply do a

@Value("${redisPort}")
private String redisPort;

int jedisPort = Integer.parseInt(redisPort.trim());

but then I get

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'secret***' defined in file [secret***.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate **** Constructor threw exception; nested exception is java.lang.NullPointerException

I have normal class names but I use "secret***" just for the example

Georgi Michev
  • 764
  • 5
  • 18
  • 37

1 Answers1

8

Simply:

@Value("${redisPort}")
private Integer redisPort;

should work. You should not do any parsing yourself, it will be taken care for you by higher forces.

NiVeR
  • 9,644
  • 4
  • 30
  • 35
  • I did try but then there is TypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer' – Georgi Michev Aug 28 '18 at 18:56
  • Are you sure that the reading of `jedisHostName` works? If it does, I don't see how the other one won't work. One thing you could check is whether you have some strange characters in `redisPort` (besides digits). – NiVeR Aug 28 '18 at 19:05
  • It works 100% because I build the project and everything was running as intended. I forgot to move the port into application.properties though and I did it afterwards and I can't figure way to do it. It is clean redisPort=6379 without spaces or other characters. Not only this but I have 4 String properties that work, but only showed one for shorter example. Whole idea is that those Strings were hard-coded and I needed to move them to application.properties – Georgi Michev Aug 28 '18 at 19:09