Spring 之 ParameterNameDiscoverer 方法參數名稱解析
1、簡介
Spring 中通過 ParameterNameDiscoverer 獲取方法中參數的名稱,它有有兩個幾個默認的實現。其中:
-
PrioritizedParameterNameDiscoverer
用來管理 Spring 中注冊的所有的 ParameterNameDiscoverer 解析器,內部維護了一個 List 集合,只要有解析參數名稱成功的就返回,從而保證了優先級順序。其子類DefaultParameterNameDiscoverer
默認往這個集合中注冊了 KotlinReflectionParameterNameDiscoverer、StandardReflectionParameterNameDiscoverer、LocalVariableTableParameterNameDiscoverer 三個解析器。 -
StandardReflectionParameterNameDiscoverer
使用 JDK 的 Parameter 解析參數名稱,關於 JDK 中參數解析見 <>。 -
LocalVariableTableParameterNameDiscoverer
使用 ASM 類庫解析參數名稱。
源碼如下:
public interface ParameterNameDiscoverer { /** * Return parameter names for a method, or {@code null} if they cannot be determined. * <p>Individual entries in the array may be {@code null} if parameter names are only * available for some parameters of the given method but not for others. However, * it is recommended to use stub parameter names instead wherever feasible. * @param method the method to find parameter names for * @return an array of parameter names if the names can be resolved, * or {@code null} if they cannot */ @Nullable String[] getParameterNames(Method method); /** * Return parameter names for a constructor, or {@code null} if they cannot be determined. * <p>Individual entries in the array may be {@code null} if parameter names are only * available for some parameters of the given constructor but not for others. However, * it is recommended to use stub parameter names instead wherever feasible. * @param ctor the constructor to find parameter names for * @return an array of parameter names if the names can be resolved, * or {@code null} if they cannot */ @Nullable String[] getParameterNames(Constructor<?> ctor); }
2、使用示例
/** * @Author dw * @ClassName ParameterDiscoverTest * @Description * @Date 2022/1/10 15:19 * @Version 1.0 */ @SpringBootTest public class ParameterDiscoverTest { @Test public void testParameterNameDiscoverer() { ParameterNameDiscoverer discoverer = new DefaultParameterNameDiscoverer(); Method method = ReflectionUtils.findMethod(TestController.class, "getParamName", String.class, Integer.class); String[] actualParams = discoverer.getParameterNames(method); for (String actualParam : actualParams) { System.out.println(actualParam); } } public class TestController { public String getParamName(String userName, Integer age) { System.out.println(userName); return userName; } } }