SpEL的使用

转载:https://blog.csdn.net/ya_1249463314/article/details/68484422

上边的链接里记录了很多SpEL的使用方法
这里只介绍一种SpEL对变量和函数的使用方法

public class TestSpEL {
	@Test
	public void test(){
		ExpressionParser parser =new SpelExpressionParser();
		StandardEvaluationContext context =new StandardEvaluationContext();
		context.setVariable("message", "Hello World");
		String value =parser.parseExpression("#message").getValue(context, String.class);
		assertThat(value, is("Hello World"));
	}
}

这意思是在StandardEvaluationContext里边设置了一个变量message,然后就可以使用#变量名就可以使用了

这个疑问是由spring security OAuth2引起的
.antMatchers("/oauth/pms/**").access("#oauth2.hasScope('pm_select') and hasRole('ROLE_USER')")
这里的and 表达式可以理解是SpEL的表达式,但是这个#oauth2.hasScope('pm_select')一直没搞明白是怎么回事

后经查询得知OAuth2WebSecurityExpressionHandler里边,设置了一个oauth2的变量,所以在上边可以调用oauth2的方法

protected StandardEvaluationContext createEvaluationContextInternal(Authentication authentication, FilterInvocation invocation) {
	   StandardEvaluationContext ec = super.createEvaluationContextInternal(authentication, invocation);
	   ec.setVariable("oauth2", new OAuth2SecurityExpressionMethods(authentication));
	   return ec;
}

猜你喜欢

转载自blog.csdn.net/gezilan/article/details/83027641
今日推荐