Sobes.tech
Senior

Annotated method with @PostConstruct and @Transactional. What will happen first?

sobes.tech AI

Answer from AI

The @PostConstruct annotation indicates that the method should be called after Spring creates the bean and performs dependency injections.

The @Transactional annotation manages transactions, typically wrapping the method call in a transactional context.

Order:

  1. The method with @PostConstruct is called first after bean initialization.
  2. The transactional aspect (@Transactional) starts a transaction when the method is called from outside.

If a method is annotated with both annotations and is called by Spring during initialization, then @PostConstruct will execute first, but the transaction may not be active, as the call occurs within bean initialization and not through Spring proxy.

In summary: @PostConstruct will run first, but @Transactional may not be applied when called during initialization.