5

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.

  1. I forked the Spring example of using the Kotlin DSL https://github.com/sdeleuze/spring-kotlin-functional
  2. I added a @PostConstruct to the UserHandler class. (More details below.)
  3. 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:

  1. Shouldn't I expect that @PostConstruct to be called since I'm bringing the class in as a bean?
  2. Am I missing a step?
  3. 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)
BPS
  • 1,606
  • 20
  • 37

1 Answers1

5

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.

Sébastien Deleuze
  • 5,950
  • 5
  • 37
  • 38
  • Thanks for the answer and for your repo, Sébastien Deleuze. It would also be nice to see how to combine component scan and DSL in case people want to migrate to DSL iteratively. – yuranos Mar 18 '19 at 09:34