Search code examples
springspring-bootkotlin

Get all annotation values used by a method level bean in project


I'm working on a Spring Boot project written with Kotlin that uses a custom method level annotation foo that has a String property called biz throughout the project.

@Foo(biz = "buzz")

Is there a way with Spring Boot or Kotlin to get a list of all the values used in the biz property of foo?


Solution

  • There is function on ListableBeanFactory, which can retrieve all beans with given annotation and return map with beans - key is bean name and value bean instance. Kotlin example:

    @Configuration
    class AnnotatedBeansCounterConfig(
        context: AbstractApplicationContext
    ) {
        init {
            context.getBeansWithAnnotation(Foo::class.java).forEach { beanName, bean ->
                val annotation = bean::class.findAnnotation<Foo>()
            }
        }
    }```