A simple question on SPEL collection selection.
Look at section 10.5.17 Collection Selection on this page https://docs.spring.io/spring/docs/4.3.10.RELEASE/spring-framework-reference/html/expressions.html
List<Inventor> list = (List<Inventor>) parser.parseExpression( "Members.?[Nationality == 'Serbian']").getValue(societyContext);
What i need is the selection ‘Serbian’ to come from outside and not be a fixed hard coded String.
Just for arguments sake consider that, we could get it as “selectedNationality” from the same society class from the same page in the link.
Modified class with selectedNationality
public class Society { private String name; public static String Advisors = "advisors"; public static String President = "president"; private List<Inventor> members = new ArrayList<Inventor>(); private Map officers = new HashMap(); // new selector field private String selectedNationality; ...... }
New Selection
The new selection SPEL would look like
List<Inventor> list = (List<Inventor>) parser.parseExpression( "Members.?[Nationality == selectedNationality]").getValue(societyContext);
When we try that the error is that “selectedNationality” is not a part of the Member object.
Does that mean that for collection selection in spring expression language we would need a hard coded String ? If yes does anyone know why ?
Advertisement
Answer
Found out how to do it. So the way is to use variables see 10.5.11 Variables @ [https://docs.spring.io/spring/docs/4.3.10.RELEASE/spring-framework-reference/html/expressions.html][1]
Set Variable
So in our case we wold do this set variable :
Inventor tesla = new Inventor("Nikola Tesla", "Serbian"); StandardEvaluationContext context = new StandardEvaluationContext(tesla); context.setVariable("selectedNationality ", "Serbian");
New Selection
The new selection SPEL would look like this with #selectedNationality
List<Inventor> list = (List<Inventor>) parser.parseExpression( "Members.?[Nationality == #selectedNationality]").getValue(societyContext);
Works like a charm !