Automatically add JaversSpringDataAuditable to all instances of JPARepository in Spring Boot

37 Views Asked by At
@Repository
@JaversSpringDataAuditable
public interface UserRepository extends JpaRepository<User, Integer> {

This works fine but I have a lot of repositories I need to annotate. Is there a way to configure Spring Boot so that all instances of @Repository will automatically use @JaversSpringDataAuditable?

1

There are 1 best solutions below

1
soonhankwon On BEST ANSWER

I don't know about @JaversSpringDataAuditable, but you can solve your problem by taking advantage of how Spring Boot works and annotations.

  • Solution: Create and use a custom annotation that has @Repository and @JaversSpringDataAuditable.

Here is my example code:

  • First, if you look inside the @Repository annotation, it is as follows.
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Repository {
    @AliasFor(
        annotation = Component.class
    )
    String value() default "";
}
  • Create a custom annotation that is the same as the annotation but has a different name.
  • Now add the @JaversSpringDataAuditable we want.
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
@JaversSpringDataAuditable //<- Add
public @interface CustomRepository {
    @AliasFor(
            annotation = Component.class
    )
    String value() default "";
}
  • Finally, use it as follows
@CustomRepository
public interface UserRepository extends JpaRepository<User, Integer> {}

You can also make the annotation name more beautiful (suitable for its functionality).

I hope it will be of help. thank you