spring-boot - 在 Spring Boot 中使用注释以正确格式放置数据
问题描述
我的实体中有一个包含电话号码的字段。根据项目的约定,我需要将其以 E.164 格式保存在数据库中。目前我使用@PrePersist 和@PreUpdate 注释将电话号码更改为指定格式。这种方法适用于一两个实体,但是当您必须一遍又一遍地重复它时,它变得非常容易出错。
我在想,如果我可以将代码放在注释中并且注释读取字段并在持久性之前更改其值,就像@LastModifiedDate 和注释所做的那样,那将是很棒的。我在网上搜索了这个注释的代码,但我不明白他们是如何管理它的。
如何编写一个读取字段值并在持久化之前更改它的注释,以及如何在删除等特定操作之前执行此操作(我也想在删除对象之前设置一些参数)
解决方案
您可以创建一个侦听器来检查您的自定义注释并触发适当的方法。
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface TheCustomAnnotation{
}
@Entity
@EntityListeners(TheListener.class)
public class TheEntity {
@TheCustomAnnotation
private String phoneNumber;
public class TheListener {
@PrePersist
public void prePersist(Object target) {
for(Field field : target.getClass().getDeclaredFields()){
Annotation[] annotations = field.getDeclaredAnnotations();
// Iterate annotations and check if yours is in it.
}
}
这只是一个例子。
推荐阅读
- java - Java 解析 unicode 数学。来自 JSON 的公式
- node.js - NodeJS 和文件 package.json
- html - chrome 中的 Flex 框项目没有占用父项的全宽
- amazon-web-services - 我的域无法由 AWS Route 53 以外的 DNS 提供商解析
- java - 使用它时如何处理 StackOverflowError。关键词
- java - 菜单项进入第二个活动,但不加载内容
- django - Django:从模型管理员到文档的超链接
- java - 从 ArrayList 添加搜索结果多于一项
- gradle - 从构建脚本配置 gradle 插件
- java - java中图像缩放的内存问题