mercredi 7 avril 2021

Add custom annotation to the @Entity class at runtime

I'm trying to add at runtime @EntityListeners annotation to the following entity:

@Data
@Builder
@Entity
@CustomEntityAnnotation
public class DummyEntity {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Integer id;

  @CustomFieldAnnotation
  @Column(name = "dummy_filed")
  private String dummyField;
}

I'm using custom ApplicationContextInitializer where I'm trying before the spring context is loaded to find all entity classes that are marked by @CustomEntityAnnotation and add to those classes annotation @EntityListeners(CustomListener.class) which contains @PrePersist @PreUpdate @PreRemove methods to intercept the operations with database and do some audit stuff with the fields marked with @CustomFieldAnnotation.

Reflections reflections = new Reflections("com.spai.utils.auditor");
ClassPool classPool = ClassPool.getDefault();
reflections.getTypesAnnotatedWith(AuditableEntity.class).forEach(clazz -> {
  log.info(clazz.getName());
  try {
    ClassLoader classLoader = classPool.getClassLoader();
    CtClass ctClass = classPool.makeClass(clazz.getName());
    ClassFile classFile = ctClass.getClassFile();
    ConstPool constPool = classFile.getConstPool();
    AnnotationsAttribute annotationsAttribute =
        new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
    Annotation annotation = new Annotation(EntityListeners.class.getCanonicalName(), constPool);
    ClassMemberValue value =
        new ClassMemberValue(CustomListener.class.getCanonicalName(), constPool);
    annotation.addMemberValue("value", value);
    annotationsAttribute.addAnnotation(annotation);
    classFile.addAttribute(annotationsAttribute);

    ctClass.getAnnotations(); // here annotation is present but not in clazz.getAnnotations()
    //ctClass.toClass(); // this line throws LinkageError attempted duplicate class definition for com.dummy.DummyEntity
    System.out.println();
  } catch (Exception e) {
    e.printStackTrace();
  }
}

Above in the comments in code, I described a situation I'm experiencing... what I'm missing or doing wrong? since the annotation is not appearing...





Aucun commentaire:

Enregistrer un commentaire