用于自定义类的Spring @Value属性

Goi*_*nas 9 spring

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

    ...
}
Run Code Online (Sandbox Code Playgroud)

编辑解决方案

以下是我使用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);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在应用程序的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;
}
Run Code Online (Sandbox Code Playgroud)

干杯,下午

Efe*_*man 7

你必须创建一个扩展类PropertyEditorSupport.

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