使用 @Value 获取 int 值

Geo*_*hev 1 java spring annotations

我有 application.properties 文件,我成功地使用 @Value 从中获取了字符串值。我在从中获取 int 时遇到问题。

jedisHostName=127.0.0.1
redisPort=6379
Run Code Online (Sandbox Code Playgroud)

在我的配置类中,我有

@Value("${jedisHostName}")
private String hostName;
Run Code Online (Sandbox Code Playgroud)

它工作正常,但是当我尝试

@Value("#{new Integer.parseInt('${redisPort}')}")
private Integer redisPort;
Run Code Online (Sandbox Code Playgroud)

我得到

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'secret***': Unsatisfied dependency expressed through field 'redisPort';
Run Code Online (Sandbox Code Playgroud)

我也只尝试

@Value("#{new Integer('${redisPort}')}")
Run Code Online (Sandbox Code Playgroud)

但我得到同样的例外。我什至试图简单地做一个

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

int jedisPort = Integer.parseInt(redisPort.trim());
Run Code Online (Sandbox Code Playgroud)

但后来我得到

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
Run Code Online (Sandbox Code Playgroud)

我有普通的类名,但我使用“secret***”作为例子

NiV*_*VeR 5

简单地:

@Value("${redisPort}")
private Integer redisPort;
Run Code Online (Sandbox Code Playgroud)

应该管用。你不应该自己做任何解析,它会被更高的力量照顾你。