gpt4 book ai didi

自定义类的 Spring @Value 属性

转载 作者:行者123 更新时间:2023-12-04 04:05:14 25 4
gpt4 key购买 nike

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

...
}

已编辑的解决方案

这是我如何使用 Spring 4.x API 做到的...

为 Customer 类创建了新的 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;
}

干杯,
下午

最佳答案

您必须创建一个扩展 PropertyEditorSupport 的类.

public class CustomerEditor extends PropertyEditorSupport {
@Override
public void setAsText(String text) {
Customer c = new Customer();
// Parse text and set customer fields...
setValue(c);
}
}

关于自定义类的 Spring @Value 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26063171/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com