Recently met some companies, there are some Java architecture, interview information, there is a need for small partners can be in the public number [programmers inside point], no routine to get
In the front
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! The impulse to hit people became stronger and stronger as I began to optimize the projects of some of my older brothers.
There is a pit
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!
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(a) {
return createTime;
}
public void setCreateTime(LocalDateTime createTime) {
this.createTime = createTime;
}
public Date getUpdateTime(a) {
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(a) {
return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern));
}
@Bean
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer(a) {
returnbuilder -> 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(a) {
return createTime;
}
public void setCreateTime(LocalDateTime createTime) {
this.createTime = createTime;
}
public Date getUpdateTime(a) {
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(a) {
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 {
returnLocalDateTime.parse(p.getValueAsString(), ofPattern(pattern)); }}}Copy the code
conclusion
Share a Springboot project in the development process of a small tip, but also incidentally to poke fun at the pit encountered in the project optimization, optimization of other people’s code although it is a more painful thing, but in this process can really learn a lot of skills, for personal skills is also very helpful, Because it is something that can really improve the efficiency of development.
Small benefits:
Hundreds of technical e-books, SHH ~, free for your friends. Concern public number reply [666] to get by yourself