Java 使用@value获取一个int值
我有application.properties文件,我成功地从中获得了带有@Value的字符串值。我在从中获取int时遇到问题Java 使用@value获取一个int值,java,spring,annotations,Java,Spring,Annotations,我有application.properties文件,我成功地从中获得了带有@Value的字符串值。我在从中获取int时遇到问题 jedisHostName=127.0.0.1 redisPort=6379 在我的配置类中,我有 @Value("${jedisHostName}") private String hostName; 它很好用,但当我尝试 @Value("#{new Integer.parseInt('${redisPort}')}") private Integer redi
jedisHostName=127.0.0.1
redisPort=6379
在我的配置类中,我有
@Value("${jedisHostName}")
private String hostName;
它很好用,但当我尝试
@Value("#{new Integer.parseInt('${redisPort}')}")
private Integer redisPort;
我明白了
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'secret***': Unsatisfied dependency expressed through field 'redisPort';
我也只是在尝试
@Value("#{new Integer('${redisPort}')}")
但我也有同样的例外。我甚至试着简单地做一件事
@Value("${redisPort}")
private String redisPort;
int jedisPort = Integer.parseInt(redisPort.trim());
但是我得到了
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
我有普通的类名,但我只使用secret***作为示例简单地说:
@Value("${redisPort}")
private Integer redisPort;
应该有用。您不应该自己进行任何解析,它将由更高的力量来处理。简单地说:
@Value("${redisPort}")
private Integer redisPort;
应该有用。您不应该自己进行任何解析,它将由更高的力量来处理。我尝试过,但出现了类型不匹配异常:未能将类型“java.lang.String”的值转换为所需类型“java.lang.Integer”您确定读取jedisHostName有效吗?如果是的话,我不知道另一个怎么会不起作用。您可以检查的一件事是,在redisPort中,除了数字之外,您是否还有一些奇怪的字符。它100%有效,因为我构建了项目,并且一切都按预期运行。我忘了把端口移到application.properties中,后来我就这么做了,我想不出怎么做。它是干净的redisPort=6379,不带空格或其他字符。不仅如此,我还有4个有效的字符串属性,但在较短的示例中只显示了一个。整个想法是,这些字符串是硬编码的,我需要将它们移动到application.properties。我确实尝试过,但随后出现了类型不匹配异常:未能将“java.lang.String”类型的值转换为所需的“java.lang.Integer”类型。您确定读取jedisHostName有效吗?如果是的话,我不知道另一个怎么会不起作用。您可以检查的一件事是,在redisPort中,除了数字之外,您是否还有一些奇怪的字符。它100%有效,因为我构建了项目,并且一切都按预期运行。我忘了把端口移到application.properties中,后来我就这么做了,我想不出怎么做。它是干净的redisPort=6379,不带空格或其他字符。不仅如此,我还有4个有效的字符串属性,但在较短的示例中只显示了一个。整个想法是这些字符串是硬编码的,我需要将它们移动到application.properties