- 需求:
如何如下properties填充到对应如下两个对象中呢?
customer.name=小术
customer.address=湖北_武汉_黄陂
@Data
public class Customer {
@Value("${customer.name}")
private String name;
@Value("${customer.address}")
private Address address;
}
@Data
public class Address {
private String province;
private String city;
private String country;
}
这时候就需要用到spring中的PropertyEditorRegistrar 自定义property编辑注册器了
直接上代码:
- 自定义属性编辑器,自定义属性填充规则:
public class AddressPropertyEditor extends PropertyEditorSupport {
@Override
public void setAsText(String text) throws IllegalArgumentException {
String[] s = text.split("_");
Address address = new Address();
address.setProvince(s[0]);
address.setCity(s[1]);
address.setCountry(s[2]);
setValue(address);
}
}
- 自定义属性编辑注册器:
public class AddressPropertyEditorRegistrar implements PropertyEditorRegistrar {
@Override
public void registerCustomEditors(PropertyEditorRegistry registry) {
registry.registerCustomEditor(Address.class, new AddressPropertyEditor());
}
}
- 配置类:
@Configuration
@PropertySource("classpath:customer.properties")
public class AddressPropertyConfiguration {
@Bean
public Customer customer(){
return new Customer();
}
@Bean
public CustomEditorConfigurer customerEditorConfigurer(){
CustomEditorConfigurer customerEditorConfigurer = new CustomEditorConfigurer();
customerEditorConfigurer.setPropertyEditorRegistrars(new PropertyEditorRegistrar[]{new AddressPropertyEditorRegistrar()});
return customerEditorConfigurer;
}
}
- 测试类:
public class DemoTest {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(AddressPropertyConfiguration.class);
Customer bean = context.getBean(Customer.class);
Address address = bean.getAddress();
System.out.println(bean);
}
}
- 控制台结果:
Customer(name=小术, address=Address(province=湖北, city=武汉, country=黄陂))