是否可以使用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