SpringMvc中的HandlerAdapter会对Controller层方法的参数执行 HandlerMethodArgumentResolver(对参数的解析器)中的方法.
首先HandlerMethodArgumentResolver接口主要有两个方法,supportsParameter和resolveArgument。
supportsParameter方法
boolean supportsParameter(MethodParameter parameter);
这个方法,从字面上就很好理解,返回值是boolean类型,作用是,判断Controller层中的参数,是否满足条件,满足条件则执行resolveArgument方法,不满足则跳过。
一般在supportParameter中执行getParameterAnnotations来判断是否包含这样的注解类型
关于getParameterAnnotations的理解为:
我们在使用spring操作orm层的时候常常会见到在方法的参数列表里添加注解的情况。当这种情况的时候可以使用getParameterAnnotations方法来获得这些注解。
public void testa(@TestAnnocation(pat = "5") String s,
@TestAnnocation2 @TestAnnocation(pat = "6") String s1,
String s3,
@TestAnnocation(pat = "9") String s4) {
System.out.println("------------" + s);
}
例如这个方法中有四个参数。在参数中又有注解。我们就可以用这种方法来获得
lass<TestObj> c = TestObj.class;
Method[] m = c.getMethods();
for (Method m1 : m) {
if ("testa".equals(m1.getName())) {
Annotation[][] an = m1.getParameterAnnotations();
for (Annotation[] an1 : an) {
System.out.println(an1.length + "-------------6");
for (Annotation an2 : an1) {
System.out.println(an2.annotationType().getSimpleName());
}
}
}
// Class[] mp = m1.getParameterTypes();
// for (Class mp1 : mp) {
// System.out.println(mp1.getSimpleName() + "---" + m1.getName());
// }
// System.out.println(m1.getName());
}
当我们使用这个方法的时候Annotation[][] an = m1.getParameterAnnotations();获得了一个注解的二维数组。第一个维度对应参数列表里参数的数目,第二个维度对应参数列表里对应的注解。如上图的示例方法有四个参数。则第一个维度的长度就是四。在参数列表中第二个参数有两个注解,第三个参数没有注解。则在第二个维度中他们对应的长度分别是2和0。执行结果如下。
1-------------6
TestAnnocation
2-------------6
TestAnnocation2
TestAnnocation
0-------------6
1-------------6
TestAnnocation
一并附上自定义注解的代码。
package com.test.reflection;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnocation {
public String pat() default "3";
public String value()default "0";
}
resolveArgument方法
Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception;
这个方法,在supportsParameter方法返回true的情况下才会被调用。用于处理一些业务,将返回值赋值给Controller层中的这个参数。
总结一下,HandlerMethodArgumentResolver是一个参数解析器,我们可以通过写一个类实现HandlerMethodArgumentResolver接口来实现对COntroller层中方法参数的修改。
转载于:https://blog.youkuaiyun.com/qq_33327210/article/details/78189239
转载于:https://blog.youkuaiyun.com/leon_cx/article/details/81058509