Sergey Shcherbakov
Sergey Shcherbakov

Reputation: 4778

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?

Upvotes: 4

Views: 1824

Answers (1)

Jens Schauder
Jens Schauder

Reputation: 81862

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) {
         ...
    }
}

Upvotes: 1

Related Questions