application.properties 文件包含具有子属性的属性:
status.available=00, STATUS.ALLOWED
status.forbidden=01, STATUS.FORBIDDEN
status.authdenied=05, STATUS.AUTH_DENIED
我们的想法是将这些属性添加到应用程序中:
@Configuration
@ConfigurationProperties(prefix = "status")
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.NONE)
public class StatusProperties {
private Map <String, List <String>> statusMapping;
public Map <String, List <String>> getStatusMapping () {
return statusMapping;
}
public void setStatusMapping (Map <String, List <String>> statusMapping) {
this.statusMapping = statusMapping;
}
}
问题是此Map返回为空。我一定做错了什么。也许这在Spring中甚至不可能这样做?
答案 0 :(得分:2)
我不确定您对数据类型及其分配的选择。我建议你重新考虑这个设计。
Spring无法知道,该状态。*应该映射到private Map <String, List <String>> statusMapping;
。此外,由于您的类被命名为* properties,您似乎不希望它成为@Configuration
类。请考虑以下模式:
首先,创建一个属性类来保存属性:
@ConfigurationProperties(prefix = "status")
public class StatusProperties {
private Map.Entry<Integer, String> available;
private Map.Entry<Integer, String> forbidden;
private Map.Entry<Integer, String> authdenied;
public Map.Entry<Integer, String> getAvailable() {
return available;
}
public void setAvailable(Map.Entry<Integer, String> available) {
this.available = available;
}
public Map.Entry<Integer, String> getForbidden() {
return forbidden;
}
public void setForbidden(Map.Entry<Integer, String> forbidden) {
this.forbidden = forbidden;
}
public Map.Entry<Integer, String> getAuthdenied() {
return authdenied;
}
public void setAuthdenied(Map.Entry<Integer, String> authdenied) {
this.authdenied = authdenied;
}
}
现在,您的IDE应该能够在编辑application.properties时从setter中读取文档并检查其有效性。 Spring可以自动装配字段并自动为您创建正确的数据类型。
考虑将条目映射到地图(或者,正如我已经说过的那样,更改设计)
现在,您可以在配置中使用此属性类:
@Configuration
@EnableConfigurationProperties(StatusProperties.class)
public class StatusConfiguration {
@Bean
public MyBean myBean(StatusProperties properties) {
return new MyBean(properties);
}
}
答案 1 :(得分:1)
我找到了解决方案:
application.properties :
app.statuses[0].id=00
app.statuses[0].title=STATUS.ALLOWED
app.statuses[1].id=01
app.statuses[1].title=STATUS.FORBIDDEN
app.statuses[2].id=02
app.statuses[2].title=STATUS.CONTRACT_ENDED
<强> Properties.java 强>
@Component
@ConfigurationProperties(prefix = "app")
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.NONE)
public class StatusProperties {
private List<Status> statuses = new ArrayList<>();
public List <Status> getStatuses () {
return statuses;
}
public void setStatuses (List <Status> statuses) {
this.statuses = statuses;
}
public static class Status {
private String id;
private String title;
public String getId () {
return id;
}
public void setId (String id) {
this.id = id;
}
public String getTitle () {
return title;
}
public void setTitle (String title) {
this.title = title;
}
}
}