Skip to content

Instantly share code, notes, and snippets.

@0guzhan
Created April 14, 2020 07:07
Show Gist options
  • Save 0guzhan/935965e14c2018e81af9a072930db190 to your computer and use it in GitHub Desktop.
Save 0guzhan/935965e14c2018e81af9a072930db190 to your computer and use it in GitHub Desktop.
spring expression language example
@Autowired
private Employee firstEmployee;
/*
name
#this.toString()
roles.?[level>7].![id]
roles.?[id>0].toString()
roles.![roleName]
roles.![{role_name:roleName,id:id}].toString()
#{ T(java.lang.Math).random() * 100.0 }
#{ T(java.lang.System).getenv().toString() }
*/
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println(Arrays.toString(args.getSourceArgs()));
System.out.println(firstEmployee.toString());
ExpressionParser expressionParser = new SpelExpressionParser();
SimpleEvaluationContext context = SimpleEvaluationContext
.forReadOnlyDataBinding()
.withInstanceMethods()
.build();
Scanner scanner = new Scanner(System.in);
while(true) {
try {
String line = scanner.nextLine();
Expression expression = expressionParser.parseExpression(line);
System.out.println(expression.getValue(context, firstEmployee, String.class));
} catch (Exception e) {
System.err.println("expression evaluation failed");
}
}
}
@Bean
@Qualifier("firstEmployee")
public Employee firstEmployee() {
return Employee.builder()
.id(nextLong())
.name(random(6, "abc"))
.roles(Arrays.asList(
Role.builder().id(nextLong(1000, 10000)).level(nextInt(1,11)).roleName(random(3, "xyz")).build(),
Role.builder().id(nextLong(1000, 10000)).level(nextInt(1,11)).roleName(random(3, "xyz")).build(),
Role.builder().id(nextLong(1000, 10000)).level(nextInt(1,11)).roleName(random(3, "xyz")).build(),
Role.builder().id(nextLong(1000, 10000)).level(nextInt(1,11)).roleName(random(3, "xyz")).build(),
Role.builder().id(nextLong(1000, 10000)).level(nextInt(1,11)).roleName(random(3, "xyz")).build()
))
.build();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment