是否可以使用Spring的@Value注释来读写自定义类类型的属性值?自定义类的Spring @ Value属性
例如:
@Component
@PropertySource("classpath:/data.properties")
public class CustomerService {
@Value("${data.isWaiting:#{false}}")
private Boolean isWaiting;
// is this possible for a custom class like Customer???
// Something behind the scenes that converts Custom object to/from property file's string value via an ObjectFactory or something like that?
@Value("${data.customer:#{null}}")
private Customer customer;
...
}
EDITED SOLUTION
这里是我是如何做到的使用Spring 4.x的API的...
为客户创建类的新PropertyEditorSupport类:
public class CustomerPropertiesEditor extends PropertyEditorSupport {
// simple mapping class to convert Customer to String and vice-versa.
private CustomerMap map;
@Override
public String getAsText()
{
Customer customer = (Customer) this.getValue();
return map.transform(customer);
}
@Override
public void setAsText(String text) throws IllegalArgumentException
{
Customer customer = map.transform(text);
super.setValue(customer);
}
}
然后在申请通货膨胀的ApplicationConfig类:
@Bean
public CustomEditorConfigurer customEditorConfigurer() {
Map<Class<?>, Class<? extends PropertyEditor>> customEditors =
new HashMap<Class<?>, Class<? extends PropertyEditor>>(1);
customEditors.put(Customer.class, CustomerPropertiesEditor.class);
CustomEditorConfigurer configurer = new CustomEditorConfigurer();
configurer.setCustomEditors(customEditors);
return configurer;
}
干杯, PM
Thanks Efe。这就是我一直在寻找的。我正在编辑我的初始文章以显示完整的解决方案。 – 2014-09-29 10:41:05