1 つの関連クラス
-
org.springframework.expression.spel.standard.SpelExpressionParser は SPEL 式を解析します
-
org.springframework.expression.spel.support.StandardEvaluationContext
メソッド名が式と一致することを確認します
2 例
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);
}
}
まず、SpelExpressionParser クラスを使用して式を解析し、次に StandardEvaluationContext オブジェクトを作成し、メソッド名を変数としてコンテキストに設定します。最後に、parseExpression メソッドを使用して式を解析し、getValue メソッドを使用して式の結果を取得します。この例では、式は #methodName.matches('get.*ById') で、メソッド名が「get」で始まり「Id」で終わるかどうかを確認します。
これは簡単な例であり、より多くのパターン マッチングをサポートするために必要に応じて式を調整します。