java listen to ContextRefreshedEvent

后端 未结 3 829
我寻月下人不归
我寻月下人不归 2021-02-04 09:30

I have a classX in my spring application in which I want to be able to find out if all spring beans have been initialized. To do this, I am trying to listen ContextRefreshedEven

3条回答
  •  既然无缘
    2021-02-04 10:14

    A ContextRefreshEvent occurs

    when an ApplicationContext gets initialized or refreshed.

    so you are on the right track.

    What you need to do is declare a bean definition for classX.

    Either with @Component and a component scan over the package it's in

    @Component
    public class X implements ApplicationListener {
        @Override
        public void onApplicationEvent(ContextRefreshedEvent event) {
           //do something if all apps have initialised
        }
    }
    

    or with a declaration

    
    

    Spring will detect that the bean is of type ApplicationListener and register it without any further configuration.

    Later Spring version support annotation-based event listeners. The documentation states

    As of Spring 4.2, you can register an event listener on any public method of a managed bean by using the @EventListener annotation.

    Within the X class above, you could declare an annotated method like

    @EventListener
    public void onEventWithArg(ContextRefreshedEvent event) {
    }
    

    or even

    @EventListener(ContextRefreshedEvent.class)
    public void onEventWithout() {
    
    }
    

    The context will detect this method and register it as a listener for the specified event type.

    The documentation goes into way more detail about the full feature set: conditional processing with SpEL expression, async listeners, etc.


    Just FYI, Java has naming conventions for types, variables, etc. For classes, the convention is to have their names start with an uppercase alphabetic character.

提交回复
热议问题