Java Spring配置属性-同一列表中的多态对象
我正试图通过Java Spring配置属性-同一列表中的多态对象,java,spring-boot,configurationproperties,Java,Spring Boot,Configurationproperties,我正试图通过@ConfigurationProperties将application.yaml中的配置项列表读取到配置bean中。该列表可能包含具有已定义基本类型的对象: @ConfigurationProperties("myapp") public class MyConfiguration { private Set<Point> points; } public abstract class Point { private String nam
@ConfigurationProperties
将application.yaml
中的配置项列表读取到配置bean中。该列表可能包含具有已定义基本类型的对象:
@ConfigurationProperties("myapp")
public class MyConfiguration {
private Set<Point> points;
}
public abstract class Point {
private String name;
}
public class QuantityPoint extends Point {
private Number value;
}
public class StatePoint extends Point {
private String state;
}
我发现了一些我认为可以解决这个问题的帖子,但到目前为止没有任何迹象表明这些帖子有效。我试着在Point
上的子类型上玩ConfigurationProperties(“myapp.points”)
,但正如所说:没有任何效果
老实说,我想知道解析器应该如何区分这些类型。必须有类似于缺少类型
参数的东西,类似于使用Jackson将实体转换为json的方式
目前,我正在获取点
的实例(当我删除摘要
修饰符时),并且值
和状态
字段丢失
编辑
我想我在找出需要做什么方面取得了一些进展。显然,Spring使用SnakeYaml来解析文件,该库使用yaml标记来指示类型信息,因此我的yaml应该类似于
myapp:
points:
- !!foo
name: foo
value: 5
- !!bar
name: bar
state: bar
有一些内置标签,但我需要注册我自己的。我找到了如何通过扩展AbstractConstruct
来编写自定义构造函数的信息,但我找不到任何关于如何在springboot设置的Yaml
实例中注册此构造函数的信息
我至少在这条路上走对了吗
编辑
我注意到snakeyaml的ConstructorException
在启动过程中来得太早,可能无法将我的SafeConstructor
添加到该过程中:
@Component
public class FooConstructor extends SafeConstructor {
public FooConstructor() {
this.yamlConstructors.put(new Tag("!foo"), new ConstructFoo());
}
private class ConstructFoo extends AbstractConstruct {
@Override
public Object construct(Node node) {
String val = (String) constructScalar((ScalarNode) node);
System.out.println(val);
return null;
}
}
}
链接中的示例将字符串“john,2000”转换为Employee对象。这不是我的方案。您的方案是将
地图
转换为点
。这没什么区别,嗯,这是一个很好的观点。我从来没有这样想过。我试试看,谢谢!从不调用转换器
@Component
public class FooConstructor extends SafeConstructor {
public FooConstructor() {
this.yamlConstructors.put(new Tag("!foo"), new ConstructFoo());
}
private class ConstructFoo extends AbstractConstruct {
@Override
public Object construct(Node node) {
String val = (String) constructScalar((ScalarNode) node);
System.out.println(val);
return null;
}
}
}
06:48:29.380 [restartedMain] ERROR org.springframework.boot.SpringApplication - Application run failed
org.yaml.snakeyaml.constructor.ConstructorException: could not determine a constructor for the tag !state
in 'reader', line 5, column 5:
- !foo