Waiting for a set variable in another Spring component

Viewed 63

I have a component A that asynchronously (@Async interface is used) runs the foo() method in component B. However, it may happen that the data in component B is not initialized yet and then foo() does not work correctly. Component A needs to wait for the data in component B to be initialized.

Is there any high-level solution in Spring (I don't want to play directly with threads) that will try to wait for some time to see if component B initializes and if it initializes earlier, can the foo() method run as well? Thread.sleep() works, but it always waits the whole time, which I don't need.

1 Answers

I think you could look into @DependsOn annotation that allows to postpone bean instantiation until its dependency is ready. In component B you can add a method annotated with @PostConstruct that would initialize the data, and over component A declaration you put @DependsOn:

@Configuration
class MyConfig {
  @Bean
  @DependsOn({"b"})
  public A a(){
    return new A();
  }

  @Bean
  public B b() {
    return new B();
  }

  @Bean
  public C c() {
    return new C();
  }
}

class B {
  @PostConstruct
  void init() {/*...*/}
}

class C {
  @Lazy
  @Autowired
  private A a;
  
  void foo() {
    Future<T> result = a.myAsyncMethod();
  }
}
Related