我在从 yaml 文件中读取附加属性时遇到问题(不是
application.yaml
)。我正在尝试解析字符串/字符串值的映射,但是我得到了NumberFormatException
。似乎 Spring 试图将其读取为整数。
这是地图的例子:
id:
id1: -1001978483459
id2: -1001978483457
和属性类:
@Data
@Configuration
@PropertySource("classpath:/id.yml")
public class ChatIdProperties {
@Value("#{${id}}")
Map<String, String> id;
}
我认为应该可以强制 Spring 将其解析为字符串或 long,因为 yaml 中使用的数字很大,但我不知道该怎么做。我尝试使用
!!str
标签但结果为零
应用程序.yml:
myapp:
ids:
id1: -1001978483459
id2: -1001978483457
MyAppProperties.java:
@ConfigurationProperties(prefix = "myapp")
public class MyAppProperties {
private Map<String, String> ids;
// accessors
}
Application.java:
@SpringBootApplication
@EnableConfigurationProperties(MyAppProperties.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
ApplicationListener<ApplicationReadyEvent> runnerListener(MyAppProperties myAppProperties) {
return applicationReadyEvent -> System.out.println(myAppProperties.getIds());
}
}
输出:
{id1=-1001978483459, id2=-1001978483457}
或者如果您真的需要在属性中没有“myapp”前缀的情况下执行此操作:
应用程序.yml:
id:
id1: -1001978483459
id2: -1001978483457
IdProperties.java:
@ConfigurationProperties
public class IdProperties {
private Map<String, String> id;
// accessors
}
Application.java:
@SpringBootApplication
@EnableConfigurationProperties(IdProperties.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
ApplicationListener<ApplicationReadyEvent> runnerListener(IdProperties idProperties) {
return applicationReadyEvent -> System.out.println(idProperties.getId());
}
}
输出:
{id1=-1001978483459, id2=-1001978483457}