I created some instance of same classes with:
private Instance<MyObserver> myObserverFactory;
public MyObserver getNewInstance() {
return myObserverFactory.get();
}
And my class:
// Dependent bean
public class MyObserver{
public void observe(@Observes MyEvent myEvent) { /* do something */ }
}
Instead of having "manager bean" which keeps all MyObserver instances, I would like to communicate with them with events. But with Dependant scope, events are sent every time to a new instance of MyObserver ... And with Dependant scope, I can't use:
@Observes(notifyObserver = Reception.IF_EXISTS)
So my question is: How to broadcast events between existing Dependant scoped beans? What scope can I use?
Thanks,
-Dush
从技术上讲,一种方法是使您的观察者方法静态化,但是如果您希望在事件期间对每个bean进行ping操作,那可能是相当有限的。
I think Adrian Mitev is right: it's not possible to do that I as would like.
I'm using Guava Event Bus for this purpose (be able to ping existing instance of beans). And I'm routing CDI event to it with this class:
/**
* Configure Guava Event Bus to get CDI event and broadcast them to it.
*/
@ApplicationScoped
public class GuavaEventBus {
private static final Logger LOGGER = LoggerFactory.getLogger(GuavaEventBus.class);
private static final EventBus eventBus = new EventBus();
@Produces
@ApplicationScoped
private EventBus createGuavaEventBus() {
return eventBus;
}
public void broadcastEveryEvent(@Observes Object event) {
// There are a lot of bradcasted events, it may be a good solution to filter them.
LOGGER.debug("Broadcast event: {}", event);
eventBus.post(event);
}
/** Why not registring and unregistring by CDI event? ;) */
public static void register(Object bean) {
LOGGER.debug("Register bean: {}", bean);
eventBus.register(bean);
}
public static void unregister(Object bean) {
eventBus.unregister(bean);
}
}
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.