ToStringBuilder使用
引入依赖
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
实战
import com.google.common.util.concurrent.RateLimiter;
import com.lyj.demo.utils.JacksonUtil;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.util.Date;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Slf4j
public class Student {
private Long id;
private String studentName;
private Integer age;
private Date birth;
private Date registerTime;
private Date lastUpdateTime;
private String no;
private static int INT;
public Student(Long id, String name, Integer age) {
this.id = id;
this.studentName = name;
this.age = age;
}
@Override
public String toString() {
// super.toString();
// return ToStringBuilder.reflectionToString(this);
// return JacksonUtil.toJson(this);
// 同样可以实现输出json格式的字符串
return ToStringBuilder.reflectionToString(this,ToStringStyle.JSON_STYLE);
}
实现全局样式设置
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.springframework.stereotype.Component;
/**
* @author 凌兮
* @date 2020/8/19 14:53
* 设置全局ToStringBuilder的ToString()方法输出格式为json格式,
* 在实体类中可以可以直接写ToStringBuilder.reflectionToString(this);
* 并且在日志打印时可以直接写对象名称不用再toString();
* 但是对于Date时间类型的参数,则不会加“”,则json工具格式化时,只需要在Date类型
* 参数那里用“”包住date时间即可正确格式化
*/
@Component
public class ToStringBuilderConfig {
static {
ToStringBuilder.setDefaultStyle(ToStringStyle.JSON_STYLE);
}
}
j将该配置添加到springbootbean里即可在项目启动时设置ToStringBuilder的全局样式,这样只需要在toString()方法里使用如下写法,即可实现json样式输出
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}