在以往的对象模型编码时,我们需要写一大堆的get/set以及不同的构造函数等。Lombok为我们提供了一个非常好的插件形式。
在大多数的项目中,只需要使用到以下集中Annotation就足够了,如果需要查看更多的选项,请参考: 传送门
@Getter
@Setter
@ToString
@RequiredArgsConstructor
生成final 字段的构造函数
/**
*/
@RequiredArgsConstructor
class UserVO {
private final Integer id;
private final String name;
private int age;
}
/**
* 编译后生成的代码
*/
class UserVO {
private final Integer id;
private final String name;
private int age;
public UserVO(Integer id, String name) {
this.id = id;
this.name = name;
}
}
- `@Data` 组合注解
/**
* @see Getter
* @see Setter
* @see RequiredArgsConstructor
* @see ToString
* @see EqualsAndHashCode
* @see lombok.Value
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.SOURCE)
public @interface Data {
/**
* ...
*/
String staticConstructor() default "";
}
- `@Builder` 改变原有赋值模式 - 使用前  - 使用后(建造者模式,在Feign源码中被大量使用)  - `@Slf4j` lombok 提供,等价于
public static final Logger LOGGER =
LoggerFactory.getLogger(UserCenterApplication.class);
/**
*/
@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.TYPE)
public @interface Slf4j {
/** @return The category of the constructed Logger. By default, it will use the type where the annotation is placed. */ String topic() default "";
}