Search code examples
javaspringspring-dataspring-data-rest

How to invoke @PostConstruct on request scoped bean before @HandleBeforeCreate handler?


In my Spring application I have a bean with request scope:

@Component
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class MyBean {

    @PostConstruct
    public void init() {
       ...
    }

I have also a MongoDB event handler:

@Component
@RepositoryEventHandler
public class MyEventHandler {

    @HandleBeforeCreate
    public void beforeCreateInstance(Object instance) {
        ...
    }
 }

When I call Spring Data REST endpoint to save my resource, the @HandleBeforeCreate gets invoked first and @PostConstruct gets invoked afterwards.

How can I change the order of this invocations? I'd like to invoke @PostConstruct on MyBean before the MongoDB event handlers kick in?


Solution

  • As explained in this answer, scoped beans get only initialized when the get referenced. So if MyEventHandler references a MyBean the MyBean should get initialized, including any PostConstruct processing.

    Of course, it would be weird to depend on a bean that you then don't use. That's exactly the purpose of @DependsOn. So change your MyEventHandler like this:

    @Component
    @RepositoryEventHandler
    @DependsOn("myBean")
    public class MyEventHandler {
    
        @HandleBeforeCreate
        public void beforeCreateInstance(Object instance) {
             ...
        }
    }