lombok
| 场景 | 是否推荐 | 常用注解 |
|---|---|---|
| 实体类(Entity / DO) | ✅ 强烈推荐 | @Data / @Getter / @Setter |
| DTO / VO | ✅ 强烈推荐 | @Data / @Builder |
| 构造器注入 | ✅ 强烈推荐 | @RequiredArgsConstructor |
| 日志 | ✅ 推荐 | @Slf4j |
| 工具类 | ⚠️ 有条件 | @UtilityClass |
| JPA 实体 | ⚠️ 谨慎 | 避免 @Data |
| 复杂业务对象 | ❌ 不推荐 | 少用 Lombok |
@Getter@Setter@Data
@Getter @Setter @ToString @EqualsAndHashCode @RequiredArgsConstructor
- 构造器
@NoArgsConstructor@AllArgsConstructor@RequiredArgsConstructor
@Builder
UserDTO user = UserDTO.builder() .id(1L) .username(“tom”) .email(“a@b.com”) .build();
- 日志注解
@Slf4j
private static final Logger log = LoggerFactory.getLogger(UserController.class);
@EqualsAndHashCode
Equals使用的是getClass()
hashCode() @Override public int hashCode() { int result = 1; result = 59 * result + (id == null ? 43 : id.hashCode()); result = 59 * result + (username == null ? 43 : username.hashCode()); return result; }
-
@ToString(exclude = "field1,field2") -
@NonNull构造器中自动做非空校验
@NonNull private UserMapper userMapper;
@UtilityClass类变为final,构造器私有,方法全是static
jdbcTemplate
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
jdbcTemplate.update(
"insert into employee(name, age) values (?, ?)",
"张三", 20
);
Employee emp = jdbcTemplate.queryForObject(
"select * from employee where id = ?",
new BeanPropertyRowMapper<>(Employee.class),
1
);
List<Employee> list = jdbcTemplate.query(
"select * from employee",
new BeanPropertyRowMapper<>(Employee.class)
);
Servelt框架
Filter等等也要复习,提到的频率挺高的
Jackson
这是一个将Java对象转为json字符串(序列化)以及将字符串转为java对象的工具类
- 解析大文件速度快
- 占用内存较低
- api更灵活,可以很容易进行扩展和定制 ``` yaml
1
2
3
4
5
6
7
8
9
10
* `ObjectMapper`
>这个就是我们要使用的工具类
* `String writeValueAsString(Object value)`
``` java
//这个函数对null的处理很灵活,你没给值就直接用null
//而且你直接放个Object就行,在封装方法的时候甚至可以不适用泛型,就直接用Object
T readValue(String content, Class valueType)
//我们可以这样封装来避免一直throw异常
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
private <T> T readJsonQuietly(String json, Class<T> clazz, String key) {
try {
return objectMapper.readValue(json, clazz);
} catch (Exception e) {
log.error("反序列化失败 key={} json={} err={}", key, json, e.toString());
return null;
}
}
private String writeJsonQuietly(Object obj, String key) {
try {
return objectMapper.writeValueAsString(obj);
} catch (Exception e) {
log.error("序列化失败 key={} objType={} err={}", key, obj == null ? "null" : obj.getClass().getName(), e.toString());
return null;
}
}
常用配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
private static final ObjectMapper objectMapper;
static {
// 创建ObjectMapper对象
objectMapper = new ObjectMapper();
// configure方法 配置一些需要的参数
// 转换为格式化的json 显示出来的格式美化
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
// 序列化的时候序列对象的那些属性
// JsonInclude.Include.NON_DEFAULT 属性为默认值不序列化
// JsonInclude.Include.ALWAYS 所有属性
// JsonInclude.Include.NON_EMPTY 属性为 空(“”) 或者为 NULL 都不序列化
// JsonInclude.Include.NON_NULL 属性为NULL 不序列化
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
// 反序列化时,遇到未知属性会不会报错
// true - 遇到没有的属性就报错
// false - 没有的属性不会管,不会报错
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// 如果是空对象的时候,不抛异常
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
// 忽略 transient 修饰的属性
objectMapper.configure(MapperFeature.PROPAGATE_TRANSIENT_MARKER, true);
// 去除默认时间戳格式
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
// 设置为中国北京时区
objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));
// 序列化日期格式 Date类型格式化
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
// 处理java8不同时间类型
JavaTimeModule module = new JavaTimeModule();
module.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
module.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
module.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(("HH:mm:ss"))));
module.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
module.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
module.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
// 序列换成json时,将所有的long变成string(因为js中得数字类型不能包含所有的java long值)
module.addSerializer(Long.TYPE, ToStringSerializer.instance);
module.addSerializer(Long.class, ToStringSerializer.instance);
objectMapper.registerModule(module);
}
@Test
public void testObjectMapper() throws JsonProcessingException {
User user = new User();
user.setId(1770376103094779915L);
user.setAge(20);
user.setBirthday(new Date());
user.setName("张三");
user.setAddress(null);
user.setLocalDateTime(LocalDateTime.now());
// 序列化
String jsonString = objectMapper.writeValueAsString(user);
System.out.println("序列化字符串:" + jsonString);
// 注意这里添加不存在的属性hobby,反序列化不会报错
jsonString = "{\"id\":1770376103094779915,\"age\":20,\"name\":\"张三\",\"birthday\":\"2024-07-19 11:02:19\",\"hobby\":\"打篮球\"}";
// 反序列化
User userFromJson = objectMapper.readValue(jsonString, User.class);
System.out.println("反序列化结果:" + userFromJson);
}
@Data
public class User {
private Long id;
private Integer age;
private String name;
private Date birthday;
private String address;
private LocalDateTime localDateTime;
}
常用注解@JsonProperty
有时候java对象和json字符串属性名对应不上,就可以使用这个注解来对应
@JsonAlias
指定一个属性可以接受json中多个字段的名称
@JsonIgnore
忽略一些属性
@JsonIgnoreProperties
同时忽略序列化和反序列化的一些属性
@JsonFormat
时间格式化注解
@JsonPropertyOrder
用于指定实体生成json时的属性顺序
高级特性
- List
- Map
- 自定义
上面这些内容暂时没有遇到过,等遇到了再来好好学习