Spring event listener ApplicationListener

ApplicationListener Spring event is part of the mechanism, the abstract class ApplicationEvent class with the event mechanism to complete the ApplicationContext.

If ApplicationListener presence of Bean container when calling publishEvent method ApplicationContext, corresponding Bean will be triggered. This process is to achieve a typical observer mode.

ApplicationListener source

@FunctionalInterface
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {

    /**
     * Handle an application event.
     * @param event the event to respond to
     */
    void onApplicationEvent(E event);
}

ContextRefreshedEvent monitor events
to the built-in event ContextRefreshedEvent Spring, for example, when the ApplicationContext is initialized or refreshed when triggered ContextRefreshedEvent event, here we achieve a ApplicationListener to monitor the occurrence of this event.

@Component // required for this class instantiated Bean 
public  class LearnListener the implements the ApplicationListener <ContextRefreshedEvent> { 
   @Override 
   public  void onApplicationEvent (ContextRefreshedEvent Event) {
       // print vessel accident Bean number 
      System.out.println ( "Listener number of initialization container obtained Bean: "+ event.getApplicationContext () getBeanDefinitionCount ());. 
   } 
}

Above, we will complete the realization of an event listener class and instantiated.

1, custom events and listeners

First of all custom events: NotifyEvent.

public class NotifyEvent extends ApplicationEvent {

    private String email; private String content; public NotifyEvent(Object source) { super(source); } public NotifyEvent(Object source, String email, String content) { super(source); this.email = email; this.content = content; } // 省略getter/setter方法 }

2. Define the listener NotifyListener:

@Component
public class NotifyListener implements ApplicationListener<NotifyEvent> {

    @Override
    public void onApplicationEvent(NotifyEvent event) {
        System.out.println("邮件地址:" + event.getEmail());
        System.out.println("邮件内容:" + event.getContent());
    }
}

Instantiated by listener @Component annotations, and the print-related information onApplicationEvent.
3, unit test classes:

@RunWith(SpringRunner.class)
@SpringBootTest
public class ListenerTest {

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Test
    public void testListener() {

        NotifyEvent event = new NotifyEvent("object", "[email protected]", "This is the content");

        webApplicationContext.publishEvent(event);
    }
}

执行单元测试,会发现事件发布之后,监听器方法被调用,日志被打印出来。

Guess you like

Origin www.cnblogs.com/caozx/p/11447774.html