Spring Event Publisher / Listener Example

Spring event architecture makes event publication and receives so easy. You can just configure the event publisher and listener object as Spring beans in the application context XML file. And then use them to send and receive events in your java code. This method decoupled the java event object relationships if you hardcode them in the java application. This makes event publisher and listener configurable. This article will show you how to implement them step by step.

1. Create Custom Application Event Object Class.

  1. First of all, you need to create a class to represent the Event object. Of course, you can use Spring built-in Event objects such as ContextRefreshedEvent, but those kinds of events are all triggered by the Spring system.
  2. So we will create a custom Event by extending the ApplicationEvent class. The custom event class must have a constructor with the event source object as the first parameter.
  3. This example creates the following two custom events.
  4. DepositEvent.java
    public class DepositEvent extends ApplicationEvent {
    
        private String bankCardID;
        
        private String depositDate;
        
        public String getBankCardID() {
            return bankCardID;
        }
    
        public void setBankCardID(String bankCardID) {
            this.bankCardID = bankCardID;
        }
    
        public String getDepositDate() {
            return depositDate;
        }
    
        public void setDepositDate(String depositDate) {
            this.depositDate = depositDate;
        }
    
        // Must has this constructor, the first parameter should be event source(which object trigger this event)
        public DepositEvent(Object source, String bankCardID, String depositDate) {
            // Must call this super class constructor first.
            super(source);
            this.bankCardID = bankCardID;
            this.depositDate = depositDate;
        }
    }
  5. WithdrawEvent.java
    public class WithdrawEvent extends ApplicationEvent {
    
        private String bankCardID;
        
        private String withdrawDate;
        
        public String getBankCardID() {
            return bankCardID;
        }
    
        public void setBankCardID(String bankCardID) {
            this.bankCardID = bankCardID;
        }
    
        public String getWithdrawDate() {
            return withdrawDate;
        }
    
        public void setWithdrawDate(String withdrawDate) {
            this.withdrawDate = withdrawDate;
        }
    
        // Must has this constructor, the first parameter should be event source ( which object trigger this event).
        public WithdrawEvent(Object source, String bankCardID, String withdrawDate) {
            // Must call this super class constructor first.
            super(source);
            this.bankCardID = bankCardID;
            this.withdrawDate = withdrawDate;
        }
    }
    

2. Create Custom Event Publisher By Implements ApplicationEventPublisherAware Interface.

  1. If your event publisher bean implements ApplicationEventPublisherAware Interface, you should override it’s setApplicationEventPublisher method. Spring framework will use this method to inject the system ApplicationEventPublisher object into your java code. You can use it to publish events. The publish action will spread to all custom event listeners.
  2. DepositEventPublisher.java
    public class DepositEventPublisher implements ApplicationEventPublisherAware {
    
        // Local ApplicationEventPublisher variable.
        private ApplicationEventPublisher eventPublisher;
    
        // Must override this method, Spring framework will inject ApplicationEventPublisher object automatically.
        @Override
        public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
            this.eventPublisher = applicationEventPublisher;
        }
        
        public void publishDepositEvent(String bankCardId, String depositDate)
        {
            System.out.println("Will publish deposit event, card id : " + bankCardId + " , date : " + depositDate);
            // Instantiate a new DepositEvent object.
            DepositEvent dEvent = new DepositEvent(this, bankCardId, depositDate);
            // Use Spring injected event publisher to publish the event object.
            this.eventPublisher.publishEvent(dEvent);
        }
    }
  3. WithdrawEventPublisher.java
    public class WithdrawEventPublisher implements ApplicationEventPublisherAware {
        
        // Local ApplicationEventPublisher variable.
        private ApplicationEventPublisher eventPublisher;
    
        // Must override this method, Spring framework will inject ApplicationEventPublisher object automatically.
        @Override
        public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
            this.eventPublisher = applicationEventPublisher;
        }
    
        public void publishWithdrawEvent(String bankCardId, String withdrawDate)
        {
            System.out.println("Will publish withdraw event, card id : " + bankCardId + " , date : " + withdrawDate);
            // Instantiate a new WithdrawEvent object.
            WithdrawEvent wdEvent = new WithdrawEvent(this, bankCardId, withdrawDate);
            // Use Spring injected event publisher object to publish the event object.
            this.eventPublisher.publishEvent(wdEvent);
        }
    }
    

3. Create Custom Event Listener By Implements ApplicationListener Interface.

  1. ApplicationListener is used to create a custom application event listener class. You should override it’s onApplicationEvent method.
  2. DepositEventListener.java
    // This listener will listen DepositEvent type application event.
    public class DepositEventListener implements ApplicationListener<DepositEvent> {
    
        @Override
        public void onApplicationEvent(DepositEvent event) {
            String bankCardId = event.getBankCardID();
            
            String depositDate = event.getDepositDate();
            
            System.out.println("Receive deposit event, bank info, card id : " + bankCardId + " , deposit date : " + depositDate);
    
        }
    
    }
  3. WithdrawEventListener.java
    //This listener will listen WithdrawEvent type custom event.
    public class WithdrawEventListener implements ApplicationListener<WithdrawEvent> {
    
        @Override
        public void onApplicationEvent(WithdrawEvent event) {
            
            String bankCardId = event.getBankCardID();
            
            String withdrawDate = event.getWithdrawDate();
            
            System.out.println("Receive withdraw event, bank info, card id : " + bankCardId + " , withdraw date : " + withdrawDate);
        }
    
    }
    

4. Configure Event Publisher And Listener In Application Context XML File.

  1. SpringEventBeanSettings.xml
     <!-- Define deposit event publisher and listener bean.  --> 
     <bean id="depositEventPublisherBean" class="com.dev2qa.example.spring.events.DepositEventPublisher"> </bean> 
     <bean id="depositEventListenerBean" class="com.dev2qa.example.spring.events.DepositEventListener"> </bean> 
    
     <!-- Define withdraw event publisher and listener bean.  --> 
     <bean id="withdrawEventPublisherBean" class="com.dev2qa.example.spring.events.WithdrawEventPublisher"> </bean> 
     <bean id="withdrawEventListenerBean" class="com.dev2qa.example.spring.events.WithdrawEventListener"> </bean>

5. Test Spring Custom Event Publisher And Listener.

  1. TestSpringEventPublisherAndListener.java
    public class TestSpringEventPublisherAndListener {
    
        public static void main(String[] args) {
            // Initiate Spring application context.
            ApplicationContext springAppCtx = new ClassPathXmlApplicationContext("SpringEventBeanSettings.xml");
    
            // Get deposit event publisher bean to publish event.
            DepositEventPublisher depositEventPublisherBean = (DepositEventPublisher)springAppCtx.getBean("depositEventPublisherBean");
            depositEventPublisherBean.publishDepositEvent("BOC6666666", "2017/06/08");
    
            // Get withdraw event publisher bean to publish event.
            WithdrawEventPublisher withdrawEventPublisherBean = (WithdrawEventPublisher)springAppCtx.getBean("withdrawEventPublisherBean");
            withdrawEventPublisherBean.publishWithdrawEvent("BOA1111111", "2017/08/08");
    
        }
    
    }
  2. Execution Output.

    Will publish deposit event, card id : BOC6666666 , date : 2017/06/08
    Receive deposit event, bank info, card id : BOC6666666 , deposit date : 2017/06/08
    Will publish withdraw event, card id : BOA1111111 , date : 2017/08/08
    Receive withdraw event, bank info, card id : BOA1111111 , withdraw date : 2017/08/08
    
0 0 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x