Spring judges that the method name is +API that matches the given SPEL+ expression

1 related class

  • org.springframework.expression.spel.standard.SpelExpressionParser parses SPEL expressions

  • org.springframework.expression.spel.support.StandardEvaluationContext

    Verify that the method name matches the expression

2 examples

javaCopyimport org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

public class MethodNameEvaluator {
    
    
    
  	// isMatch方法,用于判断方法名是否符合给定的SPEL表达式
    public static boolean isMatch(String methodName, String spelExpression) {
    
    
        SpelExpressionParser parser = new SpelExpressionParser();
        StandardEvaluationContext context = new StandardEvaluationContext();
        context.setVariable("methodName", methodName);
        return parser.parseExpression(spelExpression).getValue(context, Boolean.class);
    }
    
    public static void main(String[] args) {
    
    
        String methodName = "getUserById";
      	// 匹配以"get"开头,以"Id"结尾的方法名
        String spelExpression = "#methodName.matches('get.*ById')";
        boolean isMatched = isMatch(methodName, spelExpression);
      	// 输出true
        System.out.println(isMatched); 
    }
}

We first use the SpelExpressionParser class to parse the expression, then create a StandardEvaluationContext object, and set the method name as a variable to the context. Finally, we use the parseExpression method to parse the expression and the getValue method to get the result of the expression. In this example, our expression is #methodName.matches('get.*ById') which will check if the method name starts with "get" and ends with "Id".
This is a simple example, adjust the expression as needed to support more pattern matching.

Guess you like

Origin blog.csdn.net/qq_33589510/article/details/131371491