spring - Spring Boot JSON 配置返回 null
问题描述
我想将此 JSON 添加为我的 Spring 引导项目的外部配置:
{
"napas":[
{
"bankId":1,
"name":"abc",
"napasName":"xyz",
"napasId":"111"
},
{
"bankId":2,
"name":"mnk",
"napasName":"tcb",
"napasId":"2222"
},
{
"bankId":3,
"name":"qwer",
"napasName":"tyu",
"napasId":"888"
}
]
}
这是我的配置类:
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Configuration
@PropertySource(value = "classpath:napas-config.json", factory = JsonPropertySourceFactory.class)
public class NapasConfig {
private List<Napas> napas;
}
这是我的目标:
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class Napas {
private String bankId;
private String name;
private String napasName;
private String napasId;
}
当然,有一个用于绑定的 Json 属性源工厂,我认为错误来自这里,但我不确定如何修复它:
public class JsonPropertySourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource encodedResource) throws IOException {
Map readValue = new ObjectMapper().readValue(encodedResource.getInputStream(), Map.class);
return new MapPropertySource(encodedResource.getResource().getFilename(), readValue);
}
}
当我注入NapasConfig
我的服务并调用getNapas()
列表时,它返回 null!有人可以解释为什么以及如何解决这个问题!
解决方案
@ConfigurationProperties
您错过了使您的类成为配置属性类的重要注释
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Configuration
// This was missing
@ConfigurationProperties(prefix = "")
//
@PropertySource(value = "classpath:napas-config.json", factory = JsonPropertySourceFactory.class)
public class NapasConfig {
private List<Napas> napas;
}
推荐阅读
- sql-server - 我的 SQL Server 查询未返回预期结果
- excel - 如何将字符串连接到整数以用作 for 循环中的对象?
- angular - Angular 不显示手动浏览器重新加载或文件保存的更改
- excel - 当我尝试录制宏时,Excel 2016 会自行重启
- python - 如何提取张量流模型的输出?
- android - 自定义视图:在滚动视图内滑动
- python - Google Cloud ML 上传训练模型:输出的外部维度必须未知
- android - 使用 firebase 实时数据库或 firestore 为社交媒体平台设置 rss feed 或 feed
- java - 通过匹配另外两个列表中的条目来创建新的 Java 对象列表
- sql-server - SQL Exists 返回比 IN 更多的记录