我寫了一個自定義的JsonDeserializer
它包含一個自動裝配Autowired服務,具體如下:自動裝配在JsonDeserializer:SpringBeanAutowiringSupport VS HandlerInstantiator
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沒有被自動裝配。從查看其他SO答案(特別是,this one)看來有兩種方法可以使自動裝配工作。
選項1是使用SpringBeanAutowiringSupport
自定義解串器的構造函數中:
public PersonDeserializer() {
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
}
方案2是使用HandlerInstantiator
和我ObjectMapper
豆進行註冊:
@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
有什麼缺點?如果這有什麼不同,我的應用程序將每分鐘反序列化數百個對象。
任何意見/反饋表示讚賞。
你設法找到針對SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(本)的任何缺點; ? – 2016-02-03 10:38:30