我的 bean 中的 StringProperty 也有同样的问题。@remigio 的回答帮助我找到了解决方案。
所以我添加了转换器工厂:
public class StringPropertyToStringConverterFactory
implements ConverterFactory<StringProperty, String> {
@Override
public <T extends String> Converter<StringProperty, T> getConverter(final Class<T> type) {
return new StringPropertyToStringConverter<>();
}
private final class StringPropertyToStringConverter<E extends StringProperty, S extends String>
implements Converter<E, S> {
@Override
public S convert(final E s) {
if (s != null) {
return (S) s.getValue();
} else {
return null;
}
}
}
}
public class StringToStringPropertyConverterFactory
implements ConverterFactory<String, StringProperty> {
@Override
public <T extends StringProperty> Converter<String, T> getConverter(final Class<T> type) {
return new StringToStringPropertyConverter<>();
}
private final class StringToStringPropertyConverter<S extends String, E extends StringProperty>
implements Converter<S, E> {
@Override
public E convert(final S s) {
if (s != null) {
return (E) new SimpleStringProperty(s);
} else {
return null;
}
}
}
}
然后我在我的 Neo4jConfiguration 中注册了这些转换器工厂:
public class AppConfig extends Neo4jConfiguration {
public AppConfig() {
setBasePackage("org.foo.bar");
addConversionService();
}
private void addConversionService() {
ConversionServiceFactoryBean conversionService = new ConversionServiceFactoryBean();
conversionService.setConverters(
newHashSet(new StringPropertyToStringConverterFactory(),
new StringToStringPropertyConverterFactory()));
conversionService.afterPropertiesSet();
setConversionService(conversionService.getObject());
}
}
我不喜欢的是我不得不调用方法afterPropertiesSet()
。也许有更优雅的方式。但毕竟它有效并且属性被保存。