CONTEXT: I would like to create a custom annotation in Spring Boot and add extra logic for processing. I give an example with rather simplistic annotation but I want to have several of such annotations with more fine-grained control.
There are several approaches to this issue:
- Create Filter
- Create Interceptor
- Create annotation with custom processing
I have to move with the latest one as two above don't work with my use-case.
ISSUE:
I have a custom annotation in Kotlin and I want it to be registered and be checked in the runtime.
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FUNCTION)
annotation class OfflineProcessing(val allow: Bool)
REST controller is below:
@RestController
class ApiController {
@GetMapping("/api/version")
@OfflineProcessing(true)
fun apiVersion(): String {
return "0.1.0"
}
}
The idea is to have annotation per method and make conditional logic based on OflineProcessing
allowed or not.
I have tried creating elementary PostBeanProcessor
:
@Component
class OfflineProcessingAnnotationProcessor @Autowired constructor(
val configurableBeanFactory: ConfigurableListableBeanFactory
) : BeanPostProcessor {
@Throws(BeansException::class)
override fun postProcessBeforeInitialization(bean: Any, beanName: String): Any? {
println("Before processor. Bean name: $beanName, Bean: $bean. Bean factory: $configurableBeanFactory.")
return super.postProcessBeforeInitialization(bean, beanName)
}
@Throws(BeansException::class)
override fun postProcessAfterInitialization(bean: Any, beanName: String): Any? {
println("After processor. Bean name: $beanName, Bean: $bean. Bean factory: $configurableBeanFactory.")
return super.postProcessAfterInitialization(bean, beanName)
}
}
Apparently, annotation doesn't get logged among other annotations in BeanPostProcessor and I confused how to access it, so far I didn't find any other good examples without BeanPostProcessor.
Dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
Is there anything I do wrong? Or do I trying to use wrong method for the task?