如何使用MethodInvokingBean自定义Json Converter,以免从sql.TimeStamp中丢失纳秒

时间:2015-01-06 20:05:15

标签: json spring rest jackson converter

以下配置不会导致错误。然而,它并没有在Json转换器中起作用。我使用MethodInvokingBean而不是MethodInvokingFactoryBean,因为我读到第二个给了我一个新实例,我有兴趣更改RestTemplate使用的当前实例。无论如何,我尝试了一个工厂,它也没有生效。     老实说,经过几周的搜索,我想知道MapperObject使用它时是否真的可以更改RestTemplate的默认配置。默认配置是忽略纳秒,我真的问自己,当需要纳秒时,其他人是如何使用RestTemplate的。我可以通过从sql.TimeStamp更改为String来解决此问题,但这似乎不是最佳方法。如果其他人遇到类似问题,并且能够通过更改Jackson Mapper配置或其他方式使用sql.TimeStamp纳秒,我会很感激一些提示。

//一切从这里开始

ApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
_myCllientOfRestService = context.getBean(MyCllientOfRestService.class, request, response);
_myCllientOfRestService.myMethod();

// myCllientOfRestService

Public void myMethod(){
       //it is not returning the nano seconds and I am sure the nano seconds is available in rest service return side. MyReturnType object has the sql.TimeStamp variable filled in with nanoseconds in the rest service side but it is lost in client side
       _myReturnType = restTemplate.postForObject(urlRestService, myParameters,MyReturnType.class);
}

// applicationContext.xml的

<bean id="myCllientOfRestService" class="com.someCompany.mhe.log.handler.MyCllientOfRestService" scope="prototype" lazy-init="true">
 <property name="restTemplate" ref="restTemplate2" />
</bean>

      <bean id="myMIB"
          class="org.springframework.beans.factory.config.MethodInvokingBean">
          <property name="targetObject" ref="jacksonObjectMapper" />
          <property name="targetMethod" value="configure" />
          <property name="arguments">
              <list>
                  <value type="com.fasterxml.jackson.databind.SerializationFeature">WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS</value>
                  <value>true</value>
              </list>

          </property>
      </bean>

      <bean id="myMIB2"
          class="org.springframework.beans.factory.config.MethodInvokingBean">
          <property name="targetObject" ref="jacksonObjectMapper" />
          <property name="targetMethod" value="configure" />
          <property name="arguments">

              <list>
                  <value type="com.fasterxml.jackson.databind.DeserializationFeature">READ_DATE_TIMESTAMPS_AS_NANOSECONDS</value>
                  <value>true</value>
              </list>
          </property>
      </bean>

      <bean id="restTemplate2" class="org.springframework.web.client.RestTemplate" >
          <property name="messageConverters">
              <list>
                  <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                      <property name="objectMapper" ref="jacksonObjectMapper" />
                  </bean>
              </list>
          </property>
      </bean>

0 个答案:

没有答案