@Test public void testAddingRemovingAccessors() { StandardEvaluationContext ctx = new StandardEvaluationContext(); // reflective property accessor is the only one by default List<PropertyAccessor> propertyAccessors = ctx.getPropertyAccessors(); assertEquals(1,propertyAccessors.size()); StringyPropertyAccessor spa = new StringyPropertyAccessor(); ctx.addPropertyAccessor(spa); assertEquals(2,ctx.getPropertyAccessors().size()); List<PropertyAccessor> copy = new ArrayList<>(); copy.addAll(ctx.getPropertyAccessors()); assertTrue(ctx.removePropertyAccessor(spa)); assertFalse(ctx.removePropertyAccessor(spa)); assertEquals(1,ctx.getPropertyAccessors().size()); ctx.setPropertyAccessors(copy); assertEquals(2,ctx.getPropertyAccessors().size()); }
@SuppressWarnings("unchecked") private <T> T expression(String selector, Object bean) { if (selector == null) { return null; } StandardEvaluationContext evalCtx = new StandardEvaluationContext(bean); evalCtx.setBeanResolver(beanResolver); evalCtx.setPropertyAccessors(expressionPropertyAccessors); return (T) expressionParser.parseExpression(selector).getValue(evalCtx); }
/** * Creates a configured SpEL evaluation context * * @param rootObject the root object to transform * @param allowUnknownKeys flag to control what helper functions are available * @return an evaluation context hooked with helper functions and correct ACL via whitelisting */ public StandardEvaluationContext buildEvaluationContext(Object rootObject, boolean allowUnknownKeys) { ReturnTypeRestrictor returnTypeRestrictor = new ReturnTypeRestrictor(allowedReturnTypes); StandardEvaluationContext evaluationContext = new StandardEvaluationContext(rootObject); evaluationContext.setTypeLocator(new WhitelistTypeLocator()); evaluationContext.setMethodResolvers(Collections.singletonList( new FilteredMethodResolver(returnTypeRestrictor))); evaluationContext.setPropertyAccessors(Arrays.asList(new MapPropertyAccessor(allowUnknownKeys), new FilteredPropertyAccessor(returnTypeRestrictor))); try { for (Map.Entry<String, List<Class<?>>> m : registeredHelperFunctions.entrySet()) { registerFunction(evaluationContext, m.getKey(), m.getValue().toArray(new Class<?>[0])); } } catch (NoSuchMethodException e) { // Indicates a function was not properly registered. This should not happen. Please fix the faulty function LOGGER.error("Failed to register helper functions for rootObject {}", rootObject, e); } return evaluationContext; } }
evaluationContext.setTypeLocator(new WhitelistTypeLocator()); evaluationContext.setMethodResolvers(Collections.singletonList(new FilteredMethodResolver())); evaluationContext.setPropertyAccessors(Arrays.asList(new MapPropertyAccessor(allowUnknownKeys), new FilteredPropertyAccessor()));