2

We have 4 Beans BeanA, BeanB, BeanC, BeanD We have a cache in BeanA which gets filled in the @PostConstruct of BeanA. Now, BeanB also have a cache which gets filled in the @PostConstruct of BeanB.

BeanB's cache depends on the BeanA's cache. So BeanB should be created only after successfully creation of BeanA and BeanA's cache.

Can we ensure this using @DependsOn? What role does @PostContruct performs? When we say BeanA is succesfully created do we mean it's @PostConstruct has been completed successfully?

If not @DependsOn is there any other way to ensure this.

public class BeanA {
  private ConcurrentCache<> cacheA;

  @PostConstruct
  void init() {
   cache = fillingCache();
  }
}
public class BeanB {
  private ConcurrentCache<> cacheB;

  @Autowired
  private BeanA beanA;

  @PostConstruct
  void init() {
   cacheB = beanA.cacheA;
  }
}
Avinash Kharche
  • 411
  • 9
  • 25
  • 1
    No. You can't rely on `@DependsOn` for `@PostContruct` methods. `@DependsOn` only affects beans instantiation order. – Ori Dar Aug 22 '19 at 13:17
  • Is there any other way to ensure this? – Avinash Kharche Aug 22 '19 at 13:32
  • It depends on when the cache will really be utilized ... but maybe you could create a third service (prototype'd with the `ApplicationRunner` interface) that takes your beans as dependencies and coordinates the cache assignments? I don't know for sure, but I suspect the `run()` method would only be called after the `@PostConstruct` of its dependencies (your cache services). – Andrew Mack Aug 22 '19 at 14:06
  • The idea is that if cache is not filled then don't create the bean and break the server startup so that it should not receive any request. Caching makes a call to 3rd party APIs to get the data. – Avinash Kharche Aug 22 '19 at 14:12
  • Lots of things you can do. Pub/Sub Spring application event. Any java sync mechanism: latch/exchanger... or even have a third component which coordinate the other two – Ori Dar Aug 22 '19 at 14:15

0 Answers0