![](/img/trans.png)
[英]How to use spring data in spring mvc with annotation configuration
[英]Spring MVC and the @Data annotation
我使用SpringToolSuite
作為 IDE 並使用Spring MVC
進行開發。
在我的應用程序的 model 部分中,我定義了一個名為成分的 bean
import lombok.Data;
@Data
public class Ingredient {
public Ingredient(String string, String string2, Type wrap) {
// TODO Auto-generated constructor stub
}
private String id;
private String name;
private Type type;
public enum Type{
WRAP, PROTEIN, VEGGIES, CHEESE, SAUCE
}
}
當我使用來自Lombok的@Data
注釋時,我可以假設自動創建了一個帶有 3 個屬性的構造函數以及 getter 和 setter。
但是就像在 controller 中一樣,我調用new Ingredient("FLTO", "Flour Tortilla", Type.WRAP)
我在指令下得到一條紅線,並帶有一條消息,告訴我沒有帶有相關參數的構造函數。
@Data
錯誤導致SpringBoot的項目運行崩潰
Caused by: java.lang.Error: Unresolved compilation problems:
The method asList(T...) in the type Arrays is not applicable for the arguments (Ingredient, Ingredient, Ingredient, Ingredient, Ingredient, Ingredient, Ingredient, Ingredient, Ingredient, Ingredient)
The constructor Ingredient(String, String, Ingredient.Type) is undefined
.........................
@Data
注解為注解創建構造函數@RequiredArgsConstructor
@RequiredArgsConstructor
為未初始化的最終字段或使用@NonNull
注釋的字段創建構造函數。 您的字段不是final
的,也不是@NonNull
因此構造函數Ingredient(String, String, Ingredient.Type)
不會生成
如果要生成所有 args 構造函數,我會添加@AllArgsConstructor
注釋,或者您必須滿足上述條件
@Data
文檔
Equivalent to @Getter @Setter @RequiredArgsConstructor @ToString @EqualsAndHashCode.
由於您的字段未標記為final
字段,因此@RequiredArgsConstructor
未涵蓋它們
為此
final
或@AllArgsConstructor
編輯
@Data
public class Ingredient {
private final String id;
private final String name;
private final Type type;
public enum Type{
WRAP, PROTEIN, VEGGIES, CHEESE, SAUCE
}
}
被刪除為:
@Data
public class Ingredient {
private final String id;
private final String name;
private final Type type;
@java.beans.ConstructorProperties({"id", "name", "type"})
public Ingredient(String id, String name, Type type) {
this.id = id;
this.name = name;
this.type = type;
}
....
}
然后我可以使用
Ingredient test = new Ingredient("id", "name", Ingredient.Type.CHEESE);
我已經在 IDE 中嘗試了您的代碼,並且沒有錯誤。
確保在 IDE 中啟用了注釋處理。 此外,如果您使用的是 Gradle,請確保您在正確的位置有lombok
的annotationProcessor
。
構造函數不是使用數據自動創建的。 使用@RequiredArgsConstructor
將根據所需字段( final
字段)生成構造函數。
我假設您正在閱讀@Craig Walls 的“Spring in action book”。 無論如何,我有同樣的問題。 我現在實際上正在努力。
在我完全閱讀@Craig Walls 在書中所說的內容之前,沒有任何幫助:
為什么我的代碼中有這么多錯誤? 需要重申的是,使用 Lombok 時,您必須將 Lombok 插件安裝到 IDE 中。 沒有它,您的 IDE 將不會意識到 Lombok 提供了 getter、setter 和其他方法,並且會抱怨它們丟失了。 許多流行的 IDE 都支持 Lombok,包括 Eclipse、Spring Tool Suite、IntelliJ IDEA 和 Visual Studio Code。 有關如何將 Lombok 插件安裝到 IDE 的更多信息,請訪問 https://projectlombok.org/。
我可以說這么多,因為它幫助我
之后
基本上就像這里寫的那樣:
之后,所有錯誤都消失了。
我希望我能幫上忙!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.