[英]Spring data mongodb serialization of InetSocketAddress
首先:我對 Spring 非常陌生,因此如果我未能提供問題所需的所有信息,我深表歉意。 我的問題如下:我有以下類,我想在 mongoDB 中保存哪些對象
public class Subscription implements Serializable {
private String type;
private InetSocketAddress host;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public InetSocketAddress getHost() {
return host;
}
public void setHost(InetSocketAddress host) {
this.host = host;
}
public Subscription(){}
我通過定義一個 Repository 接口並將其自動裝配到我的應用程序中來做到這一點(這對另一個存儲庫工作正常)
public interface SubscriptionRepository extends MongoRepository<Subscription, String> {
}
我可以將訂閱對象保存到存儲庫中,但是通過SubscriptionRepository.findall()
將它們讀入List<Subscription>
給我一個錯誤
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [java.net.InetSocketAddress]: No default constructor found; nested exception is java.lang.NoSuchMethodException: java.net.InetSocketAddress.<init>()
查看數據庫 InetSocketAddress 對象保存的有點奇怪
{ "_id" : ObjectId("5e1a48f4a6e30c7d2089e5cd"), "type" : "test", "host" : { "holder" : { "addr" : { "holder" : { "address" : 174417169, "family" : 1 }, "_class" : "java.net.Inet4Address" }, "port" : 0 } }, "_class" : "com.example.myproject.Subscription" }
我必須更改什么才能以某種方式保存 InetSocketAddress 字段,以便我可以正確地從數據庫中檢索訂閱對象?
先感謝您
InetSocketAddress 是字符串主機名或帶有 int 端口的 InetAddress。
InetAddress 基本上是一個字節數組。
InetSocketAddress 和 InetAddress 都不能用作 java bean。
不是存儲 InetSocketAddress,而是存儲 String、byte[] 和端口。 更好的是,將 byte[] 轉換為 IP 地址的字符串表示,並僅存儲一個字符串和一個端口,字符串是主機名或 IP 地址作為字符串。 然后添加一個在需要時構造 InetSocketAddress 的方法。 還要為端口和字符串主機/地址添加 setter 和 getter。
public class Subscription implements Serializable {
private String type;
// instead of InetSocketAddress
private String host;
private int port;
public InetSocketAddress getSocketAddress() {
return new InetSocketAddress(host, port);
}
// setters and getters
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.