@Test
public void test() {
//數據
Properties properties = new Properties();
properties.put("text", "hello world");
properties.put("timeout", "#{30 * 1000L}");
properties.put("random", "${random.int}");
//數據源
MutablePropertySources propertySources = new MutablePropertySources();
propertySources.addLast(new PropertiesPropertySource("default", properties));
propertySources.addLast(new RandomValuePropertySource());
//屬性解析
PropertySourcesPropertyResolver propertyResolver = new PropertySourcesPropertyResolver(propertySources);
//表達式解析
StandardBeanExpressionResolver expressionResolver = new StandardBeanExpressionResolver();
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
//類型轉換
SimpleTypeConverter typeConverter = new SimpleTypeConverter();
String textProp = propertyResolver.resolveRequiredPlaceholders("${text}");
Object textObj = expressionResolver.evaluate(textProp, new BeanExpressionContext(factory, null));
String text = typeConverter.convertIfNecessary(textObj, String.class);
System.out.println(text);
String timeoutProp = propertyResolver.resolveRequiredPlaceholders("${timeout}");
Object timeoutObj = expressionResolver.evaluate(timeoutProp, new BeanExpressionContext(factory, null));
Long timeout = typeConverter.convertIfNecessary(timeoutObj, Long.class);
System.out.println(timeout);
String randomProp = propertyResolver.resolveRequiredPlaceholders("${random}");
Object randomObj = expressionResolver.evaluate(randomProp, new BeanExpressionContext(factory, null));
Integer random = typeConverter.convertIfNecessary(randomObj, Integer.class);
System.out.println(random);
}
自定義Spring EL解析
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.