我正在使用一个在MongoDB中存储POJO的Web服务。我想利用Mongo的'expireAfterSeconds'时间来生活功能,在一段时间后清除我的收藏中的旧文件。
最初我有一个使用以下JSON将日期发送到REST服务的实现:
{
"testIndex": "testIndex",
"name": "hello",
"date": "2016-05-09T11:00:39.639Z"
}
上面的代码在集合中创建了文档,并使用以下注释,在10秒后删除了文档。
@Indexed (expireAfterSeconds=10)
private Date date;
实现此代码后,我决定只在Java端生成日期,这意味着JSON现在如下:
{
"testIndex": "testIndex",
"name": "hello"
}
然后我使用杰克逊的JsonCreator在POJO中有一个构造函数
@JsonCreator
public TTLTestVO (@JsonProperty("testIndex") String testIndex, @JsonProperty("name") String name) {
this.testIndex = testIndex;
this.createdAt = new Date();
this.name = name;
}
从阅读文档here我相信这应该标记在创建新对象时要使用的构造函数。 testIndex和name字段将像以前一样填充。但是通过这个实现,每次我在我的mongo中检查文档时,日期值为'null'。如果我将其中一个字符串值的文本更改为“来自构造函数的hello”,则构造函数似乎不会被调用,因为JSON中包含的初始文本是添加到数据库中的内容。
POJO
`
@Document(collection =“test”)公共类TTLTestVO {
@Id private String _id;
@Indexed
private String testIndex;
@Indexed (expireAfterSeconds=10)
private Date createdAt;
private String name;
@JsonIgnore
public TTLTestVO() {
// default
}
@JsonCreator
public TTLTestVO (@JsonProperty("testIndex") String testIndex, @JsonProperty("name") String name) {
this.testIndex = "hello from the constructor";
this.name = name;
}
public String getId() {
return _id;
}
public void setId(String _id) {
this._id = _id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTestIndex() {
return testIndex;
}
public void setTestIndex(String testIndex) {
this.testIndex = testIndex;
}
public Date getDate() {
return createdAt;
}
public void setDate(Date date) {
this.createdAt = date;
}
`
答案 0 :(得分:0)
在调查了一些后,我发现问题在于@JsonCreator的Spring Framework实现 - 我删除了org.springframework.cloud.cloudfoundry.com.fasterxml.jackson.annotation
的导入并将其替换为com.fasterxml.jackson.annotation
。上面的实现现在按预期运行。
我一直无法在网上找到关于为什么弹簧版本不起作用的解释,所以如果有任何想法请让我/其他人知道