Issue
It seems that the @PostConstruct method is not called when a bean is added to the context using a Kotlin BeanDefinitionDsl.
This happened to me in my own project but to create a simple way to reproduce it, here's what I did.
- I forked the Spring example of using the Kotlin DSL https://github.com/sdeleuze/spring-kotlin-functional
- I added a @PostConstruct to the UserHandler class. (More details below.)
- I pushed the result here: https://github.com/benjishults/spring-kotlin-functional
So all you need to do is fork my repo and do a gradle run.
My questions are:
- Shouldn't I expect that @PostConstruct to be called since I'm bringing the class in as a bean?
- Am I missing a step?
- Is this a Spring bug?
If you don't want to pull my repo, here are more details about what I did. I added this to the UserHandler class:
@PostConstruct
fun afterPropertiesSet() {
System.out.println("AFTER PROPERTIES SET CALLED")
}
along with the import and the Gradle dependency.
The UserHandler bean is pulled into the context using a call to the bean method within a beans DSL like so:
fun beans() = beans {
bean<UserHandler>()
// ...
}
and this is brought into the context with:
beans().initialize(context)
Solution
GenericApplicationContext
instantiated in the Application
class does not support out of the box @PostContruct
. To make it works, you should use AnnotationConfigApplicationContext
instead and remove the exclude for spring-aop
in the Gradle build.
Answered By - Sébastien Deleuze