继之前项目,加入自定义注解解释器
1、创建自定义注解
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface MyAnnotation { String url(); String method(); }
2、创建注解解释器,继承spring的注解解释器,增强对方法的注解解释
/** * 自定义注解解释器 */ public class MyContract extends SpringMvcContract { /** * 重写spring框架中对方法注解的解释器 * 对父类方法进行增强 * @param data * @param annotation * @param method */ @Override protected void processAnnotationOnMethod(MethodMetadata data, Annotation annotation, Method method){ super.processAnnotationOnMethod(data, annotation, method); if(MyAnnotation.class.isInstance(annotation)){ MyAnnotation myAnnotation = method.getAnnotation(MyAnnotation.class); String url = myAnnotation.url(); String httpMethod = myAnnotation.method(); data.template().method(httpMethod); data.template().append(url); } } }
3、将自定义注解解释器加入spring容器
@Configuration public class BaseConfig { @Bean public Contract feignContract(){ return new MyContract(); } }
4、编写接口方法
/** * 调用自定义接口的注解 * @return */ @MyAnnotation(url = "/hello", method = "GET") String myAnnotationHello();
5、编写Controller方法
@GetMapping(value = "/hello", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public String hello(){ return iService.myAnnotationHello(); }