全局(单例)中的Guava EventBus和基于Spring Boot的Vaadin会话

时间:2018-01-27 00:48:23

标签: java session spring-boot vaadin guava

我试图将Guava EventBus作为Singleton和基于Vaadin应用程序的会话进行弹跳启动,但到目前为止我无法使其工作。基于会话的会议有效但不是单身会议。这个想法是实施全球通知服务,以便在发生新事件时通知特定用户。我试过以下:

public class Configuration{

    @Scope("singleton")
    @Bean
    public EventBus globalEventBus(){
       return new EventBus("globalEventBus");
    }

    @SessionScoped
    @Bean
    public EventBus eventBus(){
        return new EventBus();
    }
}

2 个答案:

答案 0 :(得分:0)

嘿,我这样解决了:

  1. 我将Eventbus包装在我的案例“TimeSaverEventBus”
  2. 中的自定义类中
  3. 在TimeSaverUI中,我添加了一个TimeSaverEventBus的私有实例,并添加了公共静态方法getEventBus():TimeSaverEventbus
  4. 我向TimeSaverEventbus添加了静态方法,调用timeSaverUI.getEventbus(),然后访问私有Eventbus实例。
  5. 守则如下:

    @SpringUI
    public class TimeSaverUI extends UI {
    
    private TimeSaverEventBus eventBus = new TimeSaverEventBus();
    
    @Override
    protected void init(VaadinRequest vaadinRequest) {
        TimeSaverEventBus.register(this);
        updateContent();
    }
    
    private void updateContent() {
      ...
    }
    
    ...
    
    public static TimeSaverEventBus getTimeSaverEventbus() {
        return ((TimeSaverUI) getCurrent()).eventBus;
    }
    }
    

    和EvenBusWrapper:

    public class TimeSaverEventBus implements SubscriberExceptionHandler {
    
    private final EventBus eventBus = new EventBus(this);
    
    public static void post(final Object event) {
        TimeSaverUI.getTimeSaverEventbus().eventBus.post(event);
    }
    
    public static void register(final Object object) {
        TimeSaverUI.getTimeSaverEventbus().eventBus.register(object);
    }
    
    public static void unregister(final Object object) {
        TimeSaverUI.getTimeSaverEventbus().eventBus.unregister(object);
    }
    
    @Override
    public final void handleException(final Throwable exception,
                                      final SubscriberExceptionContext context) {
        exception.printStackTrace();
    }
    }
    

    通过这种方式实现这一点,您可以通过调用TimeSaverEventBus的静态方法来注册和取消注册事件侦听器或发布事件。

    我真的希望这就是你要找的东西。

    干杯, 菲利克斯

答案 1 :(得分:0)

我认为您需要做的就是为您的bean使用一个名称。所以它会像这样工作。

public class Configuration{

 @Scope("singleton")
 @Bean(name="globalEventBus")
 public EventBus globalEventBus(){
    return new EventBus("globalEventBus");
 }

 @SessionScoped
 @Bean(name="sessionEventBus")
 public EventBus eventBus(){
     return new EventBus();
 }
}

然后当你想要自动装配时使用这个

@Autowired
@Qualifier("globalEventBus")
private EventBus globalEventBus;

@Autowired
@Qualifier("sessionEventBus")
private EventBus sessionEventBus;