美文网首页
java版spring cloud+spring boot+re

java版spring cloud+spring boot+re

作者: IT达人Q | 来源:发表于2019-06-24 10:43 被阅读0次

    电子商务平台源码请加企鹅求求:三伍三六二四柒二五玖。一 新建自定义注解MyUrl

    package org.crazyit.cloud.contract;
     
    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 MyUrl {
        //为注解配置两个属性
        String url();
        String method();
    }
    

    二 新建接口,使用MyUrl注解

    package org.crazyit.cloud.contract;
     
    public interface ContractClient {
     
        @MyUrl(url = "/hello", method = "GET")
        public String hello();
    }
    

    三 定义注解翻译器

    package org.crazyit.cloud.contract;
     
    import java.lang.annotation.Annotation;
    import java.lang.reflect.Method;
     
    import feign.Contract.BaseContract;
    import feign.MethodMetadata;
     
    public class MyContract extends BaseContract {
     
        @Override
        protected void processAnnotationOnClass(MethodMetadata data, Class<?> clz) {
            // 处理类级别注解
     
        }
     
        @Override
        protected void processAnnotationOnMethod(MethodMetadata data,
                Annotation annotation, Method method) {
            // 注解是MyUrl类型的,才处理
            if(MyUrl.class.isInstance(annotation)) {
                MyUrl myUrl = method.getAnnotation(MyUrl.class);
                String url = myUrl.url();
                String httpMethod = myUrl.method();
                data.template().method(httpMethod);
                data.template().append(url);
            }
        }
     
        @Override
        protected boolean processAnnotationsOnParameter(MethodMetadata data,
                Annotation[] annotations, int paramIndex) {
            // 处理参数级别注解
            return false;
        }
     
    }
    
    

    四 测试类

    package org.crazyit.cloud.contract;
     
    import org.crazyit.cloud.jaxrs.RsClient;
     
    import feign.Feign;
    import feign.jaxrs.JAXRSContract;
     
    public class ContractMain {
     
        public static void main(String[] args) {
            ContractClient client = Feign.builder()
                    .contract(new MyContract())
                    .target(ContractClient.class,
                    "http://localhost:8080");
            String result = client.hello();
            System.out.println(result);
        }
     
    }
    

    相关文章

      网友评论

          本文标题:java版spring cloud+spring boot+re

          本文链接:https://www.haomeiwen.com/subject/bulnqctx.html