2

When I ask the spring application context to give me the main class of my application, using applicationContext.getBeansWithAnnotation(...), I can only access two of the class annotations :

  • @SpringBootApplication
  • @EnableJpaRepositories

So if I ask for the bean with the annotation @EntityScan, the spring context correctly give me the main class, but I can not access the @EntityScan annotation, as if it was not present.

Why ?

Main class

@SpringBootApplication(scanBasePackages = "foo")
@EnableJpaRepositories(basePackages = "foo.repository", repositoryBaseClass = AppRepositoryImpl.class)
@EntityScan(basePackages = "foo.entity") // Spring annotation -> I don't see it
@MiscScan(basePackages = "foo.misc") // My own annotation -> I don't see it
public class APIApplication {

    public static void main(String[] args) {
        SpringApplication.run(APIApplication.class, args);
    }
}

Retrieving the main class from the spring application context

// I can search the main class using any of the 4 aforementioned annotations, it does not matter.
applicationContext.getBeansWithAnnotation(EntityScan.class).values().iterator().next().getClass().getAnnotations()

Note that :

  • Changing the order of the annotations does not matter.
  • APIApplication.class.getAnnotations() correctly give me all the annotations.

EDIT : The class was proxied by spring, so the get the real class and all the annotations I have to do this :

applicationContext.getBeansWithAnnotation(EntityScan.class).values().iterator().next().getClass().getSuperclass().getAnnotations()

EDIT 2 : I found a cleaner solution :

org.springframework.util.ClassUtils.getUserClass(applicationContext.getBeansWithAnnotation(EntityScan.class).values().iterator().next().getClass()).getAnnotations()
Flyout91
  • 782
  • 10
  • 31
  • 1
    Have you looked at the actual result of `.getClass()` and established that it's indeed the class you're inspecting? Also, are you sure the classes aren't being proxied? Have you tried to call `getDeclaredAnnotations()` instead? – ernest_k Mar 04 '22 at 10:44
  • Yes I think you are right, the class probably was proxied as the result of getClass() look like "foo.APIApplication$$EnhancerBySpringCGLIB$$ed20fa2e". I found a way to get the real class and thus all the annotations, see the edit of my message. Thank you. – Flyout91 Mar 04 '22 at 10:54
  • Nice... The only caveat is that this is now a little coupled with the implementation you tested with. – ernest_k Mar 04 '22 at 11:03

0 Answers0