Added SPEL support; fixes gh-917

This commit is contained in:
Marcin Grzejszczak
2018-04-05 16:36:59 +02:00
parent 13ff16e2a5
commit 76739a5b6b
3 changed files with 15 additions and 3 deletions

View File

@@ -710,6 +710,8 @@ The precedence is as follows:
. If the bean name has not been provided, try to evaluate an expression.
We search for a `TagValueExpressionResolver` bean.
The default implementation uses SPEL expression resolution.
**IMPORTANT** from Sleuth 2.0.0 you can only reference properties
from the SPEL expression. Method execution is not allowed due to security constraints.
. If we do not find any expression to evaluate, return the `toString()` value of the parameter.
==== Custom extractor

View File

@@ -21,6 +21,7 @@ import org.apache.commons.logging.LogFactory;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.SimpleEvaluationContext;
/**
* Uses SPEL to evaluate the expression. If an exception is thrown will return
@@ -35,9 +36,12 @@ class SpelTagValueExpressionResolver implements TagValueExpressionResolver {
@Override
public String resolve(String expression, Object parameter) {
try {
SimpleEvaluationContext context = SimpleEvaluationContext
.forReadOnlyDataBinding()
.build();
ExpressionParser expressionParser = new SpelExpressionParser();
Expression expressionToEvaluate = expressionParser.parseExpression(expression);
return expressionToEvaluate.getValue(parameter, String.class);
return expressionToEvaluate.getValue(context, parameter, String.class);
} catch (Exception e) {
log.error("Exception occurred while tying to evaluate the SPEL expression [" + expression + "]", e);
}

View File

@@ -27,10 +27,16 @@ public class SpelTagValueExpressionResolverTests {
@Test
public void should_use_spel_to_resolve_a_value() throws Exception {
SpelTagValueExpressionResolver resolver = new SpelTagValueExpressionResolver();
MyObject myObject = new MyObject();
myObject.name = "hello";
String resolved = resolver.resolve("length() + 1", "foo");
String resolved = resolver.resolve("name + ' world'", myObject);
then(resolved).isEqualTo("4");
then(resolved).isEqualTo("hello world");
}
public static class MyObject {
public String name;
}
@Test