最近工作,有些功能在不同的模块总是会重复的应用,于是想把特定的功能做成一个注解,打成jar包,放到自己的maven私服上面。这里做一下记录(springboot)
一. 自定义注解
-
建一个注解接口,加上对应的注解信息
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface CrawlerTimed { }
- 通过拦截器,拦截使用次注解的方法
public class CrawlerInterceptor extends HandlerInterceptorAdapter { private Logger logger = LoggerFactory.getLogger(CrawlerInterceptor.class); /** * 调用之前 * @param request * @param response * @param handler * @return * @throws Exception */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { HandlerMethod handlerMethod = (HandlerMethod)handler; Method method = handlerMethod.getMethod(); //获取此方法上的指定注解 CrawlerTimed crawlerTimed = method.getAnnotation(CrawlerTimed.class); //判断当前注解是否存在 if(crawlerTimed != null){ long millis = System.currentTimeMillis(); request.setAttribute("startTime",millis); logger.info("进入方法:"+method.getName()+" 的时间是:"+millis); } return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { HandlerMethod handlerMethod = (HandlerMethod)handler; Method method = handlerMethod.getMethod(); //获取此方法上的指定注解 CrawlerTimed crawlerTimed = method.getAnnotation(CrawlerTimed.class); //如果存在这个注解 if(crawlerTimed!=null){ long endTime = System.currentTimeMillis(); Long startTime =(Long) request.getAttribute("startTime"); long periodTime = endTime - startTime; logger.info("离开方法:"+method.getName()+" 的时间是:"+endTime); logger.info("方法:"+method.getName()+" 总计耗时:"+periodTime +"ms"); } } }
3 注册此拦截器,不然不会被spring管理
/** * 注册自定义的拦截器 */@Configurationpublic class InterceptorRegister extends WebMvcConfigurerAdapter { //创建拦截器bean @Bean public CrawlerInterceptor crawlerInterceptor(){ return new CrawlerInterceptor(); } //蒋拦截器bean注册到spring @Override public void addInterceptors(InterceptorRegistry registry){ registry.addInterceptor(crawlerInterceptor()); }}
4.resources/META-INF/spring.factories文件
若没有,则新建此文件org.springframework.boot.autoconfigure.EnableAutoConfiguration=\cn.iamcrawler.www.crawler_annotation.config.InterceptorRegister
5.打jar包