如何在@HandleBeforeCreate处理程序之前在请求作用域上调用@PostConstruct?

时间:2017-06-07 13:48:55

标签: java spring spring-data spring-data-rest

在我的Spring应用程序中,我有一个带有 request 范围的bean:

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

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

我还有一个MongoDB事件处理程序:

@Component
@RepositoryEventHandler
public class MyEventHandler {

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

当我调用Spring Data REST端点来保存我的资源时,首先调用@HandleBeforeCreate,然后调用@PostConstruct

如何更改此调用的顺序?我想在MongoDB事件处理程序启动之前在@PostConstruct上调用MyBean

1 个答案:

答案 0 :(得分:1)

作为explained in this answer, scoped beans get only initialized when the get referenced。因此,如果MyEventHandler引用MyBeanMyBean应该被初始化,包括任何PostConstruct处理。

当然,依赖于你不使用的bean会很奇怪。这正是@DependsOn的目的。所以改变你的MyEventHandler就像这样:

@Component
@RepositoryEventHandler
@DependsOn("myBean")
public class MyEventHandler {

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