2014-09-26 91 views
4

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

回答

5

你必须创建扩展PropertyEditorSupport类。

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

Thanks Efe。这就是我一直在寻找的。我正在编辑我的初始文章以显示完整的解决方案。 – 2014-09-29 10:41:05

1

这是可能的,但阅读Spring文档。你可以看到这个例子: 用法示例

@Configuration 
@PropertySource("classpath:/com/myco/app.properties") 
public class AppConfig { 
    @Autowired 
    Environment env; 

    @Bean 
    public TestBean testBean() { 
     TestBean testBean = new TestBean(); 
     testBean.setName(env.getProperty("testbean.name")); 
     return testBean; 
    } 
} 

查看详情here