Home > front end >  Spring-Boot, Get all annotation values used by a method level bean project
Spring-Boot, Get all annotation values used by a method level bean project

Time:09-30

I'm working on a Spring-Boot written with Kotlin project 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 ?

CodePudding user response:

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>()
        }
    }
}```

CodePudding user response:

You can get all the spring beans from the context. Follow this tutorial:

https://www.baeldung.com/spring-show-all-beans

Then you can use reflection to get the annotation arguments for each bean. There's an example here:

Get value of a parameter of an annotation in Java

  • Related