在java开发中,我们经常用到注解,比如@Override,@SuppressWarnings。@Override表示重写一个方法时,当方法名不对的时候就会提示报错;@SuppressWarnings表示压制你所写的方法内的警告。但是有的时候自己也想做一个自己的注解,提高代码的逼格和效率。
首先,先了解注解本质:注解相当于一种标记,在程序中加上了注解就等于为程序加上了某种标记,以后,
JAVAC编译器,开发工具和其他程序可以用反射来了解你的类以及各种元素上有无任何标记,看你有什么标记,就去干相应的事。了解之后,我们就可以先搞一个例子,这个例子就是整个项目中都要用到某个方法,我们可以把这个方法提取出来方便使用和维护(用@interface做):
1、定义自己的注解类:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ShoppingCartAnno {
public boolean flag() default true;
}
2、写一个拦截器,里边写上提取出来的代码:
拦截器配置:
<mvc:interceptor>
<mvc:mapping path="/**/*.html*"/>
<bean class="com.ShoppingCartHandlerInterceptor">
</bean>
</mvc:interceptor>
拦截器:
public class ShoppingCartHandlerInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HandlerMethod handlerMethod = (HandlerMethod) handler;
Annotation[] anno = handlerMethod.getMethod().getDeclaredAnnotations();
if (anno != null) {
for (Annotation temp : anno) {
if (temp.annotationType().equals(ShoppingCartAnno.class)) {//这个是重点
//公用代码
}
}
}
}
}
3、使用:
步骤2定义好了拦截器,拦截了所有的注解,当有@ShoppingCartAnno时就执行公用代码块;所以我们在想用到该公用代码块的方法上部写上:@ShoppingCartAnno:
@RequestMapping(value = "/myindex")
@ShoppingCartAnno
public String myindex(ModelMap modelMap,HttpServletRequest request,
HttpServletResponse response) {
}
这样就非常方便和简洁的使用公用代码块了,个人觉得挺不错的。感觉比公用代码块提出来放到一个类里边,每次调用都new 一下该类执行该方
法块要快和更有逼格!