【发布时间】:2014-04-14 05:42:34
【问题描述】:
我正在使用 Spring 4 和 Joda Datetime。 我有自定义序列化程序,并且我有用我的序列化程序注释域字段。
@JsonSerialize(using=ISODateTimeSerializer.class)
private DateTime date;
而且效果很好。
现在,我需要在序列化程序中使用我的服务。这意味着我必须使用 Spring 配置注册我的序列化程序。我尝试了几种不同的方法,但都没有奏效,注入的服务始终为空。
我有 ApplicationConfiguration 和几个 conf 类,我读到我必须制作 ObjectMapper 并注册它。我找不到指导如何做到这一点,你知道应该如何完成吗?
更新 1
我的序列化器
public class ISODateTimeSerializer extends JsonSerializer<DateTime> {
@Inject
private SecurityUtils securityUtils;
private static DateTimeFormatter formatter =
DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss");
@Override
public void serialize(DateTime value, JsonGenerator generator,
SerializerProvider arg2)
throws IOException {
UserSecurityWrapper user = securityUtils.getCurrentUser();
//... some logic
generator.writeString(formatter.withZone(dateTimeZone).print(value));
}
}
我的测试配置
@Configuration
public class ObjectMappingConfiguration {
private static final Logger log = LoggerFactory.getLogger(ObjectMappingConfiguration.class);
@Bean
public String registerOM() {
ObjectMapper mapper = new ObjectMapper();
SimpleModule testModule = new SimpleModule("MyModule", new Version(1, 0, 0, null));
testModule.addSerializer(new ISODateTimeSerializer());
mapper.registerModule(testModule);
return "OK";
}
}
谢谢
更新 2 我试过了,还是没有成功。
@Configuration
public class ObjectMappingConfiguration {
private static final Logger log = LoggerFactory.getLogger(ObjectMappingConfiguration.class);
@Bean
public Module apiJodaModule() {
return new ApiJodaModule();
}
@SuppressWarnings("serial")
private static class ApiJodaModule extends SimpleModule {
public ApiJodaModule() {
addDeserializer(DateTime.class, new ISODateTimeDeserializer());
addSerializer(DateTime.class, new ISODateTimeSerializer());
}
}
}
public class ISODateTimeSerializer extends StdScalarSerializer<DateTime> {
private static DateTimeFormatter formatter =
DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss");
@Inject
private SecurityUtils securityUtils;
public ISODateTimeSerializer() {
super(DateTime.class);
}
@Override
public void serialize(DateTime value, JsonGenerator generator,
SerializerProvider arg2)
throws IOException {
UserSecurityWrapper user = securityUtils.getCurrentUser();
//.....
generator.writeString(formatter.withZone(dateTimeZone).print(value));
}
}
【问题讨论】:
标签: java spring serialization jodatime