Recently several colleagues in the department have suffered some grievances have left, work together for three years at the time of parting quite reluctant to give up, until all the procedures done properly, after the greetings sent them out of the company, a few elder brother parting to my ghost smile, I immediately have a tight feeling of bad, this is absolutely not so simple.
When I took over the project of these big guys, it fulfilled my premonition. At the moment, I actually regretted that I didn’t beat them when I saw them off! Ha ha ha ~
The impulse to hit people became stronger and stronger as I began to optimize the projects of several of my brothers.
The technical department will organize code review and optimization every month. In the past, we used to review and optimize our own projects, but now several old brothers quit and their projects fall into my head.
One of the most painful things for a programmer to do is to take someone else’s project and polish it, because it’s not as easy as refactoring it all over again. However, military order in the front, no way hard scalp on it!
There is a pit
The first optimization point made me a little bit broken, these guys are very strong skills, I have been learning from the example, but in the project almost all the date formatting using SimpleDateFormat, like the following code implementation, emm~, how can the man who has been broken do anything, hahaha ~
SvcOrderDailyStatisticsPo orderDailyStatisticsPo = new SvcOrderDailyStatisticsPo();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date stationTime = dateFormat.parse(dateFormat.format(svcWorkOrderPo.getPayEndTime()));
orderDailyStatisticsPo.setStatisticalDate(stationTime);Copy the code
Date and java.util.Date and Java.util. Calendar do not support time zones and are not thread safe, so the calculation of dates is relatively tedious. The technical department consistently requires java.time LocalDateTime after JDK1.8. But many people still use java.util.Date and java.util.Calendar to handle dates.
Optimization scheme
Time formatting is used very frequently, how to make time formatting simple and do not repeat the wheel, so it should be abstracted out as a global date formatting process, the following is a simple introduction to several optimization schemes combined with practice.
The test address: http://127.0.0.1:8080/timeTest
@GetMapping("/timeTest")
public OrderInfo timeTest() {
OrderInfo order = new OrderInfo();
order.setCreateTime(LocalDateTime.now());
order.setUpdateTime(new Date());
return order;
}Copy the code
1. @jsonFormat annotations
Using the @jsonFormat annotation to format the time should be a basic operation, and most developers use this method, simple and convenient.
/** * @Author: xiaofu * @Description: */ public class OrderInfo { @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss") private LocalDateTime createTime; @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss") private Date updateTime; public LocalDateTime getCreateTime() { return createTime; } public void setCreateTime(LocalDateTime createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; }}Copy the code
The Date and LocalDateTime types are formatted successfully, but there is a problem. It is still cumbersome to do this. Each entity class has to annotate the Date field with @jsonFormat. Continue to read ~
2. Global Configuration (1)
${spring.jackson.date-format: YYYY-MM-DD HH: MM :ss} ${spring.jackson.date-format: YYYY-MM-DD HH: MM :ss} There is also no need to add @jsonFormat annotations to the entity class attributes.
/** * @Author: xiaofu * @Description: */ public class OrderInfo { //@JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss") private LocalDateTime createTime; //@JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss") private Date updateTime; public LocalDateTime getCreateTime() { return createTime; } public void setCreateTime(LocalDateTime createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; }}Copy the code
Just define a Configuration class with @Configuration and inject two beans to do the global date formatting, which is what I’m currently doing in my project.
/** * @Author: xiaofu * @Description: */ @Configuration public class LocalDateTimeSerializerConfig { @Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}") private String pattern; @Bean public LocalDateTimeSerializer localDateTimeDeserializer() { return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern)); } @Bean public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() { return builder -> builder.serializerByType(LocalDateTime.class, localDateTimeDeserializer()); }}Copy the code
Date and LocalDateTime can be used at the same time. The global time format is YYYY-MM-DD HH: MM :ss.
Add @JsonFormat annotations to specific field attributes, because @JsonFormat annotations have a higher priority and will be based on the time format of @JsonFormat annotations.
3. Global Configuration (2)
This global configuration is implemented in the same way as above, but note that with this configuration, the field manual configuration @jsonFormat annotation does not take effect.
/** * @Author: xiaofu * @Description: */ public class OrderInfo { //@JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss") private LocalDateTime createTime; //@JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss") private Date updateTime; public LocalDateTime getCreateTime() { return createTime; } public void setCreateTime(LocalDateTime createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; }}Copy the code
/** * @Author: xiaofu * @Description: */ @Configuration public class LocalDateTimeSerializerConfig { @Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}") private String pattern; @Bean @Primary public ObjectMapper serializingObjectMapper() { ObjectMapper objectMapper = new ObjectMapper(); JavaTimeModule javaTimeModule = new JavaTimeModule(); javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer()); javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer()); objectMapper.registerModule(javaTimeModule); return objectMapper; } public class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> { @Override public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException { gen.writeString(value.format(ofPattern(pattern))); } } public class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> { @Override public LocalDateTime deserialize(JsonParser p, DeserializationContext deserializationContext) throws IOException { return LocalDateTime.parse(p.getValueAsString(), ofPattern(pattern)); }}}Copy the code
This article shares a tip in the development process of a Springboot project, and also makes fun of the pit encountered in project optimization.
Optimizing someone else’s code can be a pain in the ass, but there are a lot of skills you can learn in the process that can help you improve your skills, because it’s something that can actually improve your development efficiency.
Wenyuan network, only for the use of learning, such as infringement, contact deletion.
I’ve compiled the interview questions and answers in PDF files, as well as a set of learning materials covering, but not limited to, the Java Virtual Machine, the Spring framework, Java threads, data structures, design patterns and more.
Follow the public account “Java Circle” for information, as well as quality articles delivered daily.