Spring @Value property for custom class

Can I use Spring @Value annotation to read and write property values โ€‹โ€‹of a custom class type?

For instance:

@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 string value via an ObjectFactory or something like that? @Value("${data.customer:#{null}}") private Customer customer; ... } 

UNITED SOLUTION

Here's how I did it using the Spring 4.x API ...

Created a new PropertyEditorSupport class for the Customer class:

 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); } } 

Then in the ApplicationConfig application class:

 @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; } 

Cheers PM

+6
source share
2 answers

You need to create a class that extends PropertyEditorSupport .

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

It is possible, but reading the Spring documentation. You can see this example: Usage example

  @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; } } 

More here

0
source

Source: https://habr.com/ru/post/975893/


All Articles