1. Person类
public class Person {
String name;
int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" + "name='" + name + '\'' + ", age=" + age + '}';
}
}
2. String2PersonConvert类
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.convert.converter.Converter;
import org.springframework.util.StringUtils;
public class String2PersonConvert implements Converter<String, Person> {
@Override
public Person convert(String source) {
String[] sources = StringUtils.tokenizeToStringArray(source,
ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
Person person = new Person();
person.setName(sources[0]);
person.setAge(Integer.valueOf(sources[1]));
return person;
}
}
3. Main主函数
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.env.MapPropertySource;
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext();
MapPropertySource mps = new MapPropertySource("homeMap", new HashMap<>());
mps.getSource().put("name", "Triagen");
//mps.getSource().put("age", "25");
mps.getSource().put("person", "${name},${age:999}");
ctx.getEnvironment().getPropertySources().addLast(mps);
ctx.getEnvironment().getConversionService().addConverter(new String2PersonConvert());
System.out.println(ctx.getEnvironment().getRequiredProperty("person", Person.class));
System.out.println(ctx.getEnvironment().resolvePlaceholders("${name},${age}"));
}
}
4. 结果输出
Person{name='Triagen', age=999}
Triagen,${age}
5. 代码简析
ctx.getEnvironment().getPropertySources().addLast(mps);
向Environment中添加mps数据源,addLast添加一个继承自PropertySource的对象,此对象通过getProperty(String name)方法获取给定name的value。
ctx.getEnvironment().getConversionService().addConverter(new String2PersonConvert());
添加转换器,将String字符串转化为具体对象,需要实现Converter接口。
ctx.getEnvironment().getRequiredProperty("person", Person.class)
方法首先从mps数据源中取得name为person的字符串"{age:999}",再进一步解析${}中name和age的值,取得name值为"Triagen",age没有取到值,取默认值999,最后在返回时发现需要返回Person类型,但是输入是String类型,通过输入输出匹配到String2PersonConvert 转换器,最终返回Person对象。
ctx.getEnvironment().resolvePlaceholders("${name},${age}")
resolvePlaceholders,顾名思义,对占位符进行解析,这里取值同样从mps中取得,name为"Triagen",age没有设置默认值,所以没有解析,返回原始占位符。