2014-09-26 72 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