Announcement Announcement Module
No announcement yet.
how to execute a method after all beans are initialized? Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • how to execute a method after all beans are initialized?


    i have quite a simple issue with which i'm struggling with for 2 days now.

    i want to perform some caching/storing method after the container is done initializing all my beans. that's because my operation is depending on several different services which are injected by @Autowired so just calling it when the containing bean is initialized is not enough.

    i tried using the init() method or a @PostConstruct annotation in my service but it turns out that not all the beans that it depends on were fully initialized at the time of the call - at least one of my dependencies has its own dependencies autowired after the call, so i get a NullPointerException while i try to use it.

    i was hoping i can resolve this by annotating that bean with @DependsOn(..dependency names..) but unfortunately it didn't help much.

    there has to be some easy way to perform some method when the Spring container is done initializing all beans, hasn't there?

  • #2
    It looks like you could use the "ApplicationListener" facility and look for the "ContextRefreshedEvent". It looks like that it is created when the context is finished loading.


    • #3
      to compliment @dkarr's answer:

      public class Loader implements ApplicationListener<ContextRefreshedEvent>{
              public void onApplicationEvent(ContextRefreshedEvent event) {
                       // do whatever you need to do here when app context is initialized / refreshed


      • #4
        thanks guys, it works.

        although this is not supposed to be the "Spring way" as far as i understand, because i'm not supposed to couple my code to Spring's interfaces. but if that's the only way to do it, i guess it's good enough.