2.1. 利用 Lombok 注解
Lombok 提供了一组有用的注解,可以用来消除 Java 类中的大量样板代码。
普通:
public class UserVO { | |
private Long id; | |
private String name; | |
public Long getId() { | |
return this.id; | |
} | |
public void setId(Long id) { | |
this.id = id; | |
} | |
public String getName() { | |
return this.name; | |
} | |
public void setName(String name) { | |
this.name = name; | |
} | |
... | |
} |
精简:
@Getter | |
@Setter | |
@ToString | |
public class UserVO { | |
private Long id; | |
private String name; | |
... | |
} |
2.2. 利用 Validation 注解
普通:
@Getter | |
@Setter | |
@ToString | |
public class UserCreateVO { | |
@NotBlank(message = "用户名称不能为空") | |
private String name; | |
@NotNull(message = "公司标识不能为空") | |
private Long companyId; | |
... | |
} | |
@Service | |
@Validated | |
public class UserService { | |
public Long createUser(@Valid UserCreateVO create) { | |
// TODO: 创建用户 | |
return null; | |
} | |
} |
精简:
@Getter | |
@Setter | |
@ToString | |
public class UserCreateVO { | |
@NotBlank(message = "用户名称不能为空") | |
private String name; | |
@NotNull(message = "公司标识不能为空") | |
private Long companyId; | |
... | |
} | |
@Service | |
@Validated | |
public class UserService { | |
public Long createUser(@Valid UserCreateVO create) { | |
// TODO: 创建用户 | |
return null; | |
} | |
} |
2.3. 利用 @NonNull 注解
Spring 的 @NonNull 注解,用于标注参数或返回值非空,适用于项目内部团队协作。只要实现方和调用方遵循规范,可以避免不必要的空值判断,这充分体现了阿里的“新六脉神剑”提倡的“因为信任,所以简单”。
普通:
public List<UserVO> queryCompanyUser(Long companyId) { | |
// 检查公司标识 | |
if (companyId == null) { | |
return null; | |
} | |
// 查询返回用户 | |
List<UserDO> userList = userDAO.queryByCompanyId(companyId); | |
return userList.stream().map(this::transUser).collect(Collectors.toList()); | |
} | |
Long companyId = 1L;List<UserVO> userList = queryCompanyUser(companyId); | |
if (CollectionUtils.isNotEmpty(userList)) { | |
for (UserVO user : userList) { | |
// TODO: 处理公司用户 | |
} | |
} |
精简:
public List<UserVO> queryCompanyUser( Long companyId) { | |
List<UserDO> userList = userDAO.queryByCompanyId(companyId); | |
return userList.stream().map(this::transUser).collect(Collectors.toList()); | |
} | |
Long companyId = 1L;List<UserVO> userList = queryCompanyUser(companyId); | |
for (UserVO user : userList) { | |
// TODO: 处理公司用户 | |
} |
2.4. 利用注解特性
注解有以下特性可用于精简注解声明:
1、当注解属性值跟默认值一致时,可以删除该属性赋值;
2、当注解只有 value 属性时,可以去掉 value 进行简写;
3、当注解属性组合等于另一个特定注解时,直接采用该特定注解。
普通:
@Lazy(true); | |
@Service(value = "userService") | |
@RequestMapping(path = "/getUser", method = RequestMethod.GET) |
精简:
@Lazy | |
@Service("userService") | |
@GetMapping("/getUser") |
正文完