首页 > 解决方案 > 在 Spring Boot 中使用注释以正确格式放置数据

问题描述

我的实体中有一个包含电话号码的字段。根据项目的约定,我需要将其以 E.164 格式保存在数据库中。目前我使用@PrePersist 和@PreUpdate 注释将电话号码更改为指定格式。这种方法适用于一两个实体,但是当您必须一遍又一遍地重复它时,它变得非常容易出错。

我在想,如果我可以将代码放在注释中并且注释读取字段并在持久性之前更改其值,就像@LastModifiedDate 和注释所做的那样,那将是很棒的。我在网上搜索了这个注释的代码,但我不明白他们是如何管理它的。

如何编写一个读取字段值并在持久化之前更改它的注释,以及如何在删除等特定操作之前执行此操作(我也想在删除对象之前设置一些参数)

标签: spring-bootannotations

解决方案


看看EntityListeners

您可以创建一个侦听器来检查您的自定义注释并触发适当的方法。

@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.
        }
    }

这只是一个例子。


推荐阅读