DefaultKeyGenerator implements KeyGenerator { @Override public String key(final String key, final String keyExpression, final JoinPoint joinPoint) { if (StringUtils.hasText(key)) { return key; } if (StringUtils.hasText(keyExpression)) { final StandardEvaluationContext context = new StandardEvaluationContext(); context.setVariable("type", type(joinPoint).getName()); context.setVariable("method", method(joinPoint).getName()); final Object[] args = joinPoint.getArgs(); if (args != null) { for (int idx = 0; idx < args.length; idx++) { context.setVariable(String.format("p%d", idx), args[idx]); } } final SpelExpressionParser parser = new SpelExpressionParser(); final Expression sExpression = parser.parseExpression(keyExpression); return sExpression.getValue(context, String.class); } return type(joinPoint).getName() + "." + method(joinPoint).getName(); }  @Override String key(final String key, final String keyExpression, final JoinPoint joinPoint);  }
@Test public void shouldGenerateWithParams() throws NoSuchMethodException { when(joinPoint.getTarget()).thenReturn(new Tested()); final MethodSignature signature = mock(MethodSignature.class); when(signature.getMethod()).thenReturn(Tested.class.getMethod("withParams", String.class, Long.class)); when(joinPoint.getSignature()).thenReturn(signature); when(joinPoint.getArgs()).thenReturn(new Object[]{"test", 10L}); assertThat(keyGenerator.key("", "#method + '-' + #p0 + '-' + #p1", joinPoint)).isEqualTo("withParams-test-10"); }
@Test public void shouldReturnSetKey() { assertThat(keyGenerator.key("predefine", "", null)).isEqualTo("predefine"); }
@Test public void shouldGenerateDefault() throws NoSuchMethodException { when(joinPoint.getTarget()).thenReturn(this); final MethodSignature signature = mock(MethodSignature.class); when(signature.getMethod()).thenReturn(this.getClass().getMethod("shouldGenerateDefault")); when(joinPoint.getSignature()).thenReturn(signature); assertThat(keyGenerator.key("", "", joinPoint)).isEqualTo("com.github.usedrarely.spring.rate.limit.key.DefaultKeyGeneratorTest.shouldGenerateDefault"); }
@Test public void shouldGenerateToKey() throws NoSuchMethodException { when(joinPoint.getTarget()).thenReturn(this); final MethodSignature signature = mock(MethodSignature.class); when(signature.getMethod()).thenReturn(this.getClass().getMethod("shouldGenerateToKey")); when(joinPoint.getSignature()).thenReturn(signature); assertThat(keyGenerator.key("", "#type", joinPoint)).isEqualTo("com.github.usedrarely.spring.rate.limit.key.DefaultKeyGeneratorTest"); }