1、首先定义一个自定义注解:MyTag.clss
package com.zdc.anation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ ElementType.FIELD, ElementType.METHOD })// ElementType.FIELD:注解放在属性上;ElementType.METHOD:注解放在方法上
@Retention(RetentionPolicy.RUNTIME)// 注解在运行时有效
public @interface MyTag {
String name() default "";
int size() default 0;
}
2、定义一个抽象类拦截器提供一些公共方法:
package com.zdc.pub;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
public abstract class PubInter<TagType extends Annotation> extends HandlerInterceptorAdapter {
private String annokey = this.getClass().getCanonicalName() + ".ANNO_KEY";
private String methodKey = this.getClass().getCanonicalName() + ".METHOD_KEY";
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
inflateWorkContext();
super.postHandle(request, response, handler, modelAndView);
}
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
inflateWorkContext();
Method method = getNativeMethod(handler);
TagType annotation = getAnnotationFromMethod(method); // 获取当前拦截方法的注解
if(method != null && annotation != null) {
this.setMethod(method);
this.setAnnotation(annotation);
}
return super.preHandle(request, response, handler);
}
private static ThreadLocal<Map<String, Object>> threas = new ThreadLocal<Map<String, Object>>();
private void inflateWorkContext() {
if(threas.get() == null) {
// 重新实例化
threas.set(new HashMap<String, Object>());
} else {
// 清空
threas.get().remove(this.annokey);
threas.get().remove(this.methodKey);
}
this.setInstance(this);
}
private Method getNativeMethod(Object handler) {
if(handler != null && handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
return handlerMethod.getMethod();
}
return null;
}
private Class<?> getclass(Object handler) {
if(handler != null && handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
return handlerMethod.getBeanType();
}
return null;
}
private Class<TagType> getAnnoClazz() {
Type superClass = this.getClass().getGenericSuperclass();
Type type = ((ParameterizedType) superClass).getActualTypeArguments()[0];
return (Class<TagType>) type;
}
private TagType getAnnotationFromMethod(Method method) {
if(method != null) {
TagType annoTag = method.getAnnotation(getAnnoClazz());
return annoTag;
}
return null;
}
private void setAnnotation(TagType annotation) {
threas.get().put(this.annokey, annotation);
}
@SuppressWarnings("unchecked")
public TagType getAnnotation() {
return (TagType) threas.get().get(this.annokey);
}
private void setMethod(Method method) {
threas.get().put(this.methodKey, method);
}
public Method getMethod() {
return (Method) threas.get().get(this.methodKey);
}
private void setInstance(@SuppressWarnings("rawtypes") PubInter instance) {
threas.get().put(this.getClass().getCanonicalName(), instance);
}
public static ThreadLocal<Map<String, Object>> getthreas() {
return threas;
}
public static void setthreas(ThreadLocal<Map<String, Object>> threas) {
PubInter.threas = threas;
}
}
3、定义注解拦截器实现上面的抽象类:
package com.zdc.pub;
import java.lang.reflect.Method;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import com.zdc.anation.MyTag;
public class CarAnno extends PubInter<MyTag> {
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
super.postHandle(request, response, handler, modelAndView);
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
boolean bol = super.preHandle(request, response, handler);
getStr(super.getMethod());
return bol;
}
private String getStr(Method method) throws Exception {
StringBuffer str = new StringBuffer("注解值:");
MyTag myTag = method.getAnnotation(MyTag.class);
str.append("值1:" + myTag.name());
str.append(";值2:" + myTag.size());
System.out.println(str.toString());
return str.toString();
}
}
4、配置拦截器:InterConfig.class
package com.zdc.config;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import com.zdc.pub.CarAnno;
@Component
@Configurable
public class InterConfig {
@Bean
public CarAnno myInter() {
return new CarAnno();
}
@Bean
public WebMvcConfigurerAdapter webMvcConfigurerAdapter() {
WebMvcConfigurerAdapter weAdapter = new WebMvcConfigurerAdapter() {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new CarAnno()).addPathPatterns("/**");
super.addInterceptors(registry);
}
};
return weAdapter;
}
}
5、定义一个controller:AnnoController.class
package com.zdc.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.zdc.anation.MyTag;
@RestController
public class AnnoController {
@RequestMapping(value = "/mycar")
@MyTag(name = "大众", size = 200)
public String mycars() {
return "123";
}
}