Spring MVC and the @Data annotation


  • 我使用SpringToolSuite作为IDE,使用Spring MVC进行开发。

  • 在我的应用程序的模型部分,我定义了一个名为Ingredient

    的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
}
}
  • 当我使用@Data注释时,来自Lombok我可以假设自动创建了一个包含这3个属性的构造函数,以及getter和setter。

  • 但是在控制器中,我调用new Ingredient("FLTO", "Flour Tortilla", Type.WRAP),我在指令下得到一条红线,其中有一条消息告诉我没有具有所讨论参数的构造函数。

    • 我不明白,因为类Ingredient被标记为龙目表的注释@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文档

Equivalent to @Getter @Setter @RequiredArgsConstructor @ToString @EqualsAndHashCode.

由于您的字段没有标记为final,因此它们不被@RequiredArgsConstructor

覆盖因此

  1. 将必需的字段声明为final
  2. 使用@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);

@Data注释为@RequiredArgsConstructor注释创建构造函数

@RequiredArgsConstructor为未初始化的final字段或带有@NonNull注释的字段创建构造函数。您的字段不是final也不是@NonNull,因此构造函数Ingredient(String, String, Ingredient.Type)不会生成

如果你想生成所有参数构造器,我会添加@AllArgsConstructor注释,或者你必须满足上述条件

我已经在IDE中尝试了您的代码,没有错误。

确保在IDE中启用了注释处理。此外,如果你使用Gradle,确保你有annotationProcessorlombok在正确的位置。

构造函数不是通过使用data自动创建的。使用@RequiredArgsConstructor将生成一个基于所需字段(final字段)的构造函数。

我猜您正在阅读@Craig Walls的"春季行动手册"。不管怎样,我也有同样的问题。我现在正在做呢。

没有任何帮助,直到我读了@Craig Walls在书中所说的:

为什么我的代码中有这么多错误?这是值得重复的使用Lombok时,必须将Lombok插件安装到IDE中。如果没有它,您的IDE将不会意识到Lombok正在提供getter,setter和其他方法,并且会抱怨它们丢失了。许多流行的ide都支持Lombok,包括Eclipse、Spring Tool Suite, IntelliJ IDEA和Visual Studio Code。访问有关如何安装的更多信息,请访问https://projectlombok .org/将Lombok插件放到IDE中。

我可以说这么多,因为它帮助我。

  • 从https://projectlombok.org/
  • 下载
  • 从命令行启动jar文件(管理员权限)
  • 重启STS(或其他IDE)
  • 后来

  • 在STS中验证项目(在包资源管理器中右键单击)
  • 更新maven项目。(在包资源管理器中右键点击)

基本上就像这里写的:

之后所有错误都消失了。

希望我能帮上忙!

最新更新