我编写了一个包含 Autowiring 服务的自定义 JsonDeserializer,如下所示:
public class PersonDeserializer extends JsonDeserializer<Person> {
@Autowired
PersonService personService;
@Override
public Person deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
// deserialization occurs here which makes use of personService
return person;
}
}
当我第一次使用这个反序列化器时,我得到了 NPE,因为 personService 没有被 Autowiring 。通过查看其他 SO 答案(特别是 this one ),似乎有两种方法可以使 Autowiring 工作。
选项 1 是在自定义反序列化器的构造函数中使用 SpringBeanAutowiringSupport:
public PersonDeserializer() {
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
}
选项 2 是使用 HandlerInstantiator 并将其注册到我的 ObjectMapper bean:
@Component
public class SpringBeanHandlerInstantiator extends HandlerInstantiator {
@Autowired
private ApplicationContext applicationContext;
@Override
public JsonDeserializer<?> deserializerInstance(DeserializationConfig config, Annotated annotated, Class<? extends JsonDeserializer<?>> deserClass) {
try {
return (JsonDeserializer<?>) applicationContext.getBean(deserClass);
} catch (Exception e) {
// Return null and let the default behavior happen
return null;
}
}
}
@Configuration
public class JacksonConfiguration {
@Autowired
SpringBeanHandlerInstantiator springBeanHandlerInstantiator;
@Bean
public ObjectMapper objectMapper() {
Jackson2ObjectMapperFactoryBean jackson2ObjectMapperFactoryBean = new Jackson2ObjectMapperFactoryBean();
jackson2ObjectMapperFactoryBean.afterPropertiesSet();
ObjectMapper objectMapper = jackson2ObjectMapperFactoryBean.getObject();
// add the custom handler instantiator
objectMapper.setHandlerInstantiator(springBeanHandlerInstantiator);
return objectMapper;
}
}
我已经尝试了这两种选择,它们同样有效。显然选项 1 要简单得多,因为它只有三行代码,但我的问题是:与 HandlerInstantiator 方法相比,使用 SpringBeanAutowiringSupport 有什么缺点吗?我的应用程序将每分钟反序列化数百个对象,如果这有什么不同的话。
欢迎任何建议/反馈。
最佳答案
添加到 Amir Jamak 的回答中,您不必创建自定义 HandlerInstantiator,因为 Spring 已经拥有它,即 SpringHandlerInstantiator。
您需要做的是在 Spring 配置中将其连接到 Jackson2ObjectMapperBuilder。
@Bean
public HandlerInstantiator handlerInstantiator(ApplicationContext applicationContext) {
return new SpringHandlerInstantiator(applicationContext.getAutowireCapableBeanFactory());
}
@Bean
public Jackson2ObjectMapperBuilder objectMapperBuilder(HandlerInstantiator handlerInstantiator) {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.handlerInstantiator(handlerInstantiator);
return builder;
}
关于java - JsonDeserializer : SpringBeanAutowiringSupport vs HandlerInstantiator 中的 Autowiring ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28393599/