lombok构造模式
这种方法比自己写Builder类方便多了
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class DemoModel {
private String name;
private int age;
private int start;
private int end;
}
Data注解的解释
/**
* Generates getters for all fields, a useful toString method, and hashCode and equals implementations that check
* all non-transient fields. Will also generate setters for all non-final fields, as well as a constructor.
* <p>
* Equivalent to {@code @Getter @Setter @RequiredArgsConstructor @ToString @EqualsAndHashCode}.
* <p>
* Complete documentation is found at <a href="https://projectlombok.org/features/Data">the project lombok features page for @Data</a>.
*
* @see Getter
* @see Setter
* @see RequiredArgsConstructor
* @see ToString
* @see EqualsAndHashCode
* @see lombok.Value
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.SOURCE)
public @interface Data {
/**
* If you specify a static constructor name, then the generated constructor will be private, and
* instead a static factory method is created that other classes can use to create instances.
* We suggest the name: "of", like so:
*
* <pre>
* public @Data(staticConstructor = "of") class Point { final int x, y; }
* </pre>
*
* Default: No static constructor, instead the normal constructor is public.
*
* @return Name of static 'constructor' method to generate (blank = generate a normal constructor).
*/
String staticConstructor() default "";
}
@Builder会按builder模式生成一个内部类,具体使用如下
DemoModel model = DemoModel.builder()
.name("builder")
.age(-1)
.build();
注意需要写@NoArgsConstructor
这时候我们就需要添加无参构造方法,因为java序列化默认是需要一个无参构造方法。
这个情况是因为我们原来的IOC容器都是通过反射来获取对象实例,而对象实例一般都是单例的形式出现,这时候就需要通过无参构造方法来提供支持。