使用垃圾方法写一个不知道有没有鸟用的按profile来决定是否执行的@JsonIgnore

我们知道对一个对象进行JSON序列化的时候,如果某个字段不想要序列化返回,那么可以在字段上添加一个注解JsonIgnore,那么最终就会在序列化的时候忽略这个字段。

但是如果在springboot项目中,想要根据不同的profile来决定要不要输出呢?

工具使用的是Jackson

这个需求可能没什么鸟用,这次用到也是因为项目内容定义了很多错误码以及错误原因。但是某个接口是对外提供服务的,然后本身接口也会返回错误码和错误原因,但是输出给调用方的只是一些与参数或者数据相关的错误,而系统内部相关的错误是不输出给外部的。所以就在项目内部定义了内部code码和外部code码的映射关系。然后为了方便测试人员发现具体错误就将这个内部对象也放到了输出对象中,格式就类似如下,internalRes这个字段对外是不返回的,因此就需要进行环境区分,只有生产环境时需要忽略。

@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class OutApiResponse<T> implements Serializable {
    private static final long serialVersionUID = -4894732146235457654L;
    /**
     * 响应状态码,使用的是httpStatus
     */
    private Integer code;

    /**
     * 错误消息
     */
    private String message;

    /**
     * 返回数据明细
     *
     * @see OutTextResponseBody
     */
    private T data;

    /**
     * 内部响应码,测试用
     */
    @JsonIgnoreProfile(profile = {EnvironmentConstants.PROD})
    private InternalRes internalRes;

    /**
     * 内部实际错误状态码,这个最终不会暴露给第三方,但是开发的时候暴露出来,方便测试
     */
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    static class InternalRes {
        private Integer code;
        private String message;
    }
}

自带的JsonIgnore肯定是不支持这个需求的,但是有没有提供扩展呢?于是就想着看jackson对这个注解的处理有没有提供扩展点,但是以个人有限的水平一番找下去之后是没有找到的。Jackson判断字段是否要忽略的代码如下
com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector#_isIgnorable

public class JacksonAnnotationIntrospector
        extends AnnotationIntrospector
        implements java.io.Serializable
{
	 protected boolean _isIgnorable(Annotated a) {
	     JsonIgnore ann = _findAnnotation(a, JsonIgnore.class);
	     if (ann != null) {
	         return ann.value();
	     }
	     if (_java7Helper != null) {
	         Boolean b = _java7Helper.findTransient(a);
	         if (b != null) {
	             return b.booleanValue();
	         }
	     }
	     return false;
 	 }
}

看到方式是protected 的就想能不能重写,然后就发现了这个类,JacksonAnnotationIntrospector被静态fianl变量直接指定给了DEFAULT_ANNOTATION_INTROSPECTOR, 然后在赋值给了DEFAULT_BASE

public class ObjectMapper
    extends ObjectCodec
    implements Versioned,
        java.io.Serializable // as of 2.1
{
	    // 16-May-2009, tatu: Ditto ^^^
    protected final static AnnotationIntrospector DEFAULT_ANNOTATION_INTROSPECTOR = new JacksonAnnotationIntrospector();

    /**
     * Base settings contain defaults used for all {@link ObjectMapper}
     * instances.
     */
    protected final static BaseSettings DEFAULT_BASE = new BaseSettings(
            null, // cannot share global ClassIntrospector any more (2.5+)
            DEFAULT_ANNOTATION_INTROSPECTOR,
             null, TypeFactory.defaultInstance(),
            null, StdDateFormat.instance, null,
            Locale.getDefault(),
            null, // to indicate "use Jackson default TimeZone" (UTC since Jackson 2.7)
            Base64Variants.getDefaultVariant(), // 2.1
            LaissezFaireSubTypeValidator.instance
    );
    public ObjectMapper(JsonFactory jf,
            DefaultSerializerProvider sp, DefaultDeserializationContext dc)
    {
       	// 删除前后代码
        BaseSettings base = DEFAULT_BASE.withClassIntrospector(defaultClassIntrospector());
    }
}

行吧, 既然不提供方法替换,那么整体替换BaseSettings 行不行呢, 然后就发现了这个DEFAULT_BASE是在ObjectMapper的构造方法中直接引用的,也没提供入参。看到这里就没办法了, 那就想用最少改动的地方,直接把JacksonAnnotationIntrospector这个类的源码拷贝到项目中,然后重写_isIgnorable方法总行吧,这就是说的用的最垃圾的方法了。
注意如果要复制一个类的源码进行重写,一定要保证这个类的包路径和原类路径保持一致
JacksonAnnotationIntrospector的源码拷贝到自己项目的com.fasterxml.jackson.databind.introspect包路径下
其实采用覆盖这个源码的方法就没什么好的说头了

先定义一个注解用以接收环境变量的值

@Target({ElementType.ANNOTATION_TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotation
public @interface JsonIgnoreProfile {

    boolean value() default true;

    /**
     * 要满足的环境,当value为true且profile满足时才忽略字段的序列化
     * @return
     */
    String[] profile() default {};
}

修改原方法如下. 原逻辑依然支持
如果一个字段没有@JsonIgnore 标注的时候再判断我们自定义的注解@JsonIgnoreProfile
然后取出里面的pfoile的值,和当前应用配置的profile比较,看是否包含在里面就可以了。

关于SpringContextHolder其实就是实现了ApplicationContextAware方便在无spring ioc环境中获取bean而已。
EnvironmentHelper其实就是写的用于一个判断传入的profile列表是否包含在当前激活的profile而已

    protected boolean _isIgnorable(Annotated a)
    {
        JsonIgnore ann = _findAnnotation(a, JsonIgnore.class);
        if (ann != null) {
            return ann.value();
        }
        if (_java7Helper != null) {
            Boolean b = _java7Helper.findTransient(a);
            if (b != null) {
                return b.booleanValue();
            }
        }

        // 扩展原JsonIgnore, 现支持可以根据不同的profile来决定是否忽略
        JsonIgnoreProfile jsonIgnoreProfile = _findAnnotation(a, JsonIgnoreProfile.class);
        if (jsonIgnoreProfile != null && jsonIgnoreProfile.value() && jsonIgnoreProfile.profile() != null) {
            EnvironmentHelper environmentHelper = SpringContextHolder.getApplicationContext().getBean(EnvironmentHelper.class);
            return environmentHelper.checkIsExistOr(Arrays.asList(jsonIgnoreProfile.profile()));
        }
        return false;
    }

至此总算完成了这个操作,先凑合用吧,反正我不说,谁知道是这样实现的呢。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值