Skip to content

Instantly share code, notes, and snippets.

@FrancescoJo
Created May 26, 2022 12:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FrancescoJo/c36b67c3c2b310ed58e2f28b2187e22e to your computer and use it in GitHub Desktop.
Save FrancescoJo/c36b67c3c2b310ed58e2f28b2187e22e to your computer and use it in GitHub Desktop.
Spring Framework Custom annotation as Bean loader
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory
import org.springframework.beans.factory.support.BeanDefinitionRegistry
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider
import org.springframework.context.annotation.Configuration
import org.springframework.core.type.filter.AnnotationTypeFilter
@Configuration
class AnnotationConfig : BeanDefinitionRegistryPostProcessor {
override fun postProcessBeanFactory(beanFactory: ConfigurableListableBeanFactory) {
}
override fun postProcessBeanDefinitionRegistry(registry: BeanDefinitionRegistry) {
val scanner = ClassPathScanningCandidateComponentProvider(false)
scanner.addIncludeFilter(AnnotationTypeFilter(MyAnnotation::class.java))
// Speedup for specific package names
scanner.findCandidateComponents("PACKAGE_NAME")
.forEach {
// According to the documentation using this as bean name here could be dangerous,
// but using this value is safe unless annotated class is a simple(a final type) object.
val name = it.beanClassName!!
registry.registerBeanDefinition(name, it)
}
}
}
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
@MustBeDocumented
annotation class MyAnnotation
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment