欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

解决feign接口返回泛型设置属性为null的问题

程序员文章站 2022-03-11 12:25:36
简介feign是一种声明式http请求调用方式,工作原理就是根据feignclient注解生成新的接口(也就是传说中的动态代理),常见使用方式如下所示:@feignclient(name="userf...

简介

feign是一种声明式http请求调用方式,工作原理就是根据feignclient注解生成新的接口(也就是传说中的动态代理),常见使用方式如下所示:

@feignclient(name="userfeignservice",url="${auth.url}",
        fallbackfactory = orgfeignservicefallback.class,
        configuration = feignerrordecoderconfiguration.class)
public interface orgfeignservice {
 
    /**
     * 
     * @param org
     * @return
     */
    @postmapping(value="tenant/addtenantorg", consumes="application/json; charset=utf-8")
    apiresultto<tenantorg> addorg(orgdto org, @requestheader("token")string token);
}

应用场景

1、序列化以及反序列化采用jackson

2、调用第三方采用feign注解式接口

问题分析

apiresultto是一个api通用接口返回泛型类,tenantorg为传入的具体泛型类,咱们来看下出问题的类:

@getter
@setter
@noargsconstructor
public class tenantorg {
    /**
     */
    @jsonproperty("id")
    private string id;
    /**
     * 父级id
     */
    @jsonproperty("pid")
    private string pid;
    /**
     * 租户代码
     */
    @jsonproperty("tenant")
    private string tenant;
    /**
     * 组织架构名字
     */
    @jsonproperty("name")
    private string name;
}

必须要用@jsonproperty("id")或者@jsonsetter("id")注解来显示声明属性名字,尤其是首字母为大写的情况,否则反序列化后的数据就为空值。

为什么tenantorg类中的id等其他属性跟第三方服务返回的json数据字段完全一致,却没有成功设置对应的属性呢,这个就要看下beandeserializer类的deserializefromobject方法,从其名字上我们可以看出这是将请求返回的数据反序列化成对应的类对象:

public object deserializefromobject(jsonparser p, deserializationcontext ctxt) throws ioexception
    {
        /* 09-dec-2014, tatu: as per [databind#622], we need to allow object id references
         *   to come in as json objects as well; but for now assume they will
         *   be simple, single-property references, which means that we can
         *   recognize them without having to buffer anything.
         *   once again, if we must, we can do more complex handling with buffering,
         *   but let's only do that if and when that becomes necessary.
         */
        if ((_objectidreader != null) && _objectidreader.mayserializeasobject()) {
            if (p.hastokenid(jsontokenid.id_field_name)
                    && _objectidreader.isvalidreferencepropertyname(p.getcurrentname(), p)) {
                return deserializefromobjectid(p, ctxt);
            }
        }
        if (_nonstandardcreation) {
            if (_unwrappedpropertyhandler != null) {
                return deserializewithunwrapped(p, ctxt);
            }
            if (_externaltypeidhandler != null) {
                return deserializewithexternaltypeid(p, ctxt);
            }
            object bean = deserializefromobjectusingnondefault(p, ctxt);
            if (_injectables != null) {
                injectvalues(ctxt, bean);
            }
            /* 27-may-2014, tatu: i don't think view processing would work
             *   at this point, so commenting it out; but leaving in place
             *   just in case i forgot something fundamental...
             */
            /*
            if (_needviewprocesing) {
                class<?> view = ctxt.getactiveview();
                if (view != null) {
                    return deserializewithview(p, ctxt, bean, view);
                }
            }
            */
            return bean;
        }
        final object bean = _valueinstantiator.createusingdefault(ctxt);
        // [databind#631]: assign current value, to be accessible by custom deserializers
        p.setcurrentvalue(bean);
        if (p.canreadobjectid()) {
            object id = p.getobjectid();
            if (id != null) {
                _handletypedobjectid(p, ctxt, bean, id);
            }
        }
        if (_injectables != null) {
            injectvalues(ctxt, bean);
        }
        if (_needviewprocesing) {
            class<?> view = ctxt.getactiveview();
            if (view != null) {
                return deserializewithview(p, ctxt, bean, view);
            }
        }
        if (p.hastokenid(jsontokenid.id_field_name)) {
            string propname = p.getcurrentname();
            do {
                p.nexttoken();
                //如果要跟踪测试的话,直接定位到该位置就可以,你就会发现如果没有
                //jsonproperty之类的注解定义属性名字的话,id、pid属性在_beanproperties都成了小写的属性
                settablebeanproperty prop = _beanproperties.find(propname);
                if (prop != null) { // normal case
                    try {
                        prop.deserializeandset(p, ctxt, bean);
                    } catch (exception e) {
                        wrapandthrow(e, bean, propname, ctxt);
                    }
                    continue;
                }
                handleunknownvanilla(p, ctxt, bean, propname);
            } while ((propname = p.nextfieldname()) != null);
        }
        return bean;
    }

具体如下图所示:

解决feign接口返回泛型设置属性为null的问题

正如上面所示,用@jsonproperty注解配置的属性,在反序列化时就按照@jsonproperty注解定义的属性名相同,至于为什么在tenantorg中定义的pid属性在使用时怎么变成了pid,

具体可以看下pojopropertiescollector类的_removeunwantedproperties方法以及_renameproperties方法:

    protected void _removeunwantedproperties(map<string, pojopropertybuilder> props)
    {
        iterator<pojopropertybuilder> it = props.values().iterator();
        while (it.hasnext()) {
            pojopropertybuilder prop = it.next();
 
            // 去除private属性,pid属性会在这里移除
            if (!prop.anyvisible()) {
                it.remove();
                continue;
            }
            // otherwise, check ignorals
            if (prop.anyignorals()) {
                // first: if one or more ignorals, and no explicit markers, remove the whole thing
                if (!prop.isexplicitlyincluded()) {
                    it.remove();
                    _collectignorals(prop.getname());
                    continue;
                }
                // otherwise just remove ones marked to be ignored
                prop.removeignored();
                if (!prop.coulddeserialize()) {
                    _collectignorals(prop.getname());
                }
            }
        }
    }
protected void _renameproperties(map<string, pojopropertybuilder> props)
    {
        // with renaming need to do in phases: first, find properties to rename
        iterator<map.entry<string,pojopropertybuilder>> it = props.entryset().iterator();
        linkedlist<pojopropertybuilder> renamed = null;
        while (it.hasnext()) {
            map.entry<string, pojopropertybuilder> entry = it.next();
            pojopropertybuilder prop = entry.getvalue();
 
            //被@jsonproperty注解的属性会找到对应的属性名
            collection<propertyname> l = prop.findexplicitnames();
 
            // no explicit names? implicit one is fine as is
            if (l.isempty()) {
                continue;
            }
            it.remove(); // need to replace with one or more renamed
            if (renamed == null) {
                renamed = new linkedlist<pojopropertybuilder>();
            }
            // simple renaming? just do it
            //在这里使用@jsonproperty注解里面定义的属性名,比如pid、id等
            //所以使用了@jsonproperty注解后,我们就无需关注类里面属性的大小写,设置不用关注属性名
            if (l.size() == 1) {
                propertyname n = l.iterator().next();
                renamed.add(prop.withname(n));
                continue;
            }
            // but this may be problematic...
            renamed.addall(prop.explode(l));
 
            /*
            string newname = prop.findnewname();
            if (newname != null) {
                if (renamed == null) {
                    renamed = new linkedlist<pojopropertybuilder>();
                }
                prop = prop.withsimplename(newname);
                renamed.add(prop);
                it.remove();
            }
            */
        }
        
        // and if any were renamed, merge back in...
        if (renamed != null) {
            for (pojopropertybuilder prop : renamed) {
                string name = prop.getname();
                pojopropertybuilder old = props.get(name);
                if (old == null) {
                    props.put(name, prop);
                } else {
                    old.addall(prop);
                }
                // replace the creatorproperty too, if there is one
                _updatecreatorproperty(prop, _creatorproperties);
                // [databind#2001]: new name of property was ignored previously? remove from ignored
                // 01-may-2018, tatu: i have a feeling this will need to be revisited at some point,
                //   to avoid removing some types of removals, possibly. but will do for now.
                if (_ignoredpropertynames != null) {
                    _ignoredpropertynames.remove(name);
                }
            }
        }
    }

springcloud feign请求:数据返回null

问题描述

调用方调用服务,debug被调用方服务得到正确数据,但调用方返回的数据对象属性全为null

解决feign接口返回泛型设置属性为null的问题

原因及解决方法:

在feign调用接口中与被调用方接口返回类型不一致

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。