简体   繁体   中英

Multiple instances of a bean

I'm implementing a listener class which listens for some events and then processes them. If processing of this event goes well then this event is never notified again, but in case of any exception event will be again notified to MyBeanImplementation class after some time and it can again try processing it.

Following code works fine but since this event processing may take some time,
1. I want to have multiple listeners.
2. Limit number of calls to service, may be using threadpool.

How can I have multiple listeners which will process each event differently? I'm new to Spring and don't have much idea if this is even possible or not.

Heres is an example:

// Spring Configuration:

<bean id="MyBean" class="MyBeanImplementation">

// Sample Class

public class MyBeanImplementation implements EventListener {

    @override
    public processEvent(Event event) throws EventProcessFailureException {
        try {
            // Validate event
            validateEvent(event);
            // Call another service to store part of information from this event
            // This service takes some time to return success
            boolean success = makeCallToServiceAndStoreInfo(event);
            if(!success) {
                throw new EventProcessFailureException("Error storing event information!");
            }
        } catch (Exception e) {
            throw new EventProcessFailureException(e);
        }
    }

}


Thanks

Basically, you can use Strategy pattern to introduce different listeners that re-act in a different way to a shared event.

<bean id="strategy1Listener" />
<bean id="strategy2Listener" />
<bean id="strategy3Listener" />

Then, you can introduce a composite listener to iterate through other listeners and pass through the event and allow them to process the event:

<bean id="compositeStrategyListener">
  <property name="listeners">
    <list>
      <ref bean="strategy1Listener" />
      <ref bean="strategy2Listener" />
      <ref bean="strategy3Listener" />
    </list>
  </property>
</bean>

On the other side of the story, you have an object that generates/publishes the events:

<bean id="eventGenerator">
  <property name="eventListener" ref="compositeStrategyListener" />
</bean>

So, now eventGenerator publishes the generated event to a compositeStrategyListner which iterates over the listeners it has and allows them to process the event in their own different way.

You can also take advantage of Spring Task Execution to configure how you need to run the task of event processing.

Why not using google guava eventbus library with spring together? It will handle every thing needed for listening events.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM