Spring Doc中如何为Schema正确应用Mixins与序列化组件?
解决SpringDoc未应用Jackson Mixins/序列化器的问题
针对你遇到的Swagger UI Schema示例错误、请求体未应用Mixins的问题,给你几个可行的解决方案:
方案1:直接注入Spring容器中配置好的ObjectMapper创建ModelResolver
你之前用Jackson2ObjectMapperBuilder.build()会生成新的ObjectMapper实例,没有带上你配置的Mixins和自定义序列化器。直接注入Spring上下文里已配置完成的ObjectMapper即可:
@Bean public ModelResolver modelResolver(ObjectMapper objectMapper) { return new ModelResolver(objectMapper); }
这个方法会让SpringDoc直接使用你项目中已经配置好所有Mixins、序列化器的ObjectMapper,自动同步Model的Schema定义。
方案2:批量注册Mixins到SpringDoc
如果方案1不生效,可以通过代码批量读取ObjectMapper中的Mixins配置,自动同步到SpringDoc,避免逐个手动替换:
@Configuration public class SpringDocMixinConfig { @Autowired private ObjectMapper objectMapper; @PostConstruct public void registerMixinsToSpringDoc() { SpringDocUtils docConfig = SpringDocUtils.getConfig(); // 遍历ObjectMapper中所有已注册的Mixins,批量替换 objectMapper.getMixInAnnotations().forEach((targetClass, mixinClass) -> { docConfig.replaceWithClass(targetClass, mixinClass); }); } }
方案3:确保全局只有一个ObjectMapper实例
如果项目中存在多个ObjectMapper实例,可能导致ModelResolver拿到的不是配置好的那个。可以给自定义的ObjectMapper加上@Primary注解,确保它是Spring优先使用的实例:
@Bean @Primary public ObjectMapper customObjectMapper(Jackson2ObjectMapperBuilder builder) { ObjectMapper mapper = builder.build(); // 在这里统一配置你的Mixins、序列化器/反序列化器 mapper.addMixIn(Money.class, MoneyMixin.class); // 其他Jackson配置... return mapper; } // 再用这个@Primary的ObjectMapper创建ModelResolver @Bean public ModelResolver modelResolver(ObjectMapper customObjectMapper) { return new ModelResolver(customObjectMapper); }
完成配置后重启应用,检查Swagger UI中的Money Schema是否与Mixins定义的结构一致,再用Try it out测试请求是否能正常解析。
内容的提问来源于stack exchange,提问作者mdanish98
相关产品推荐
相关产品推荐

