Inject vaadin @UIScope bean in spring @Component

4.5k Views Asked by At

I am using Vaadin Spring 1.0.0 and trying to figure out how could I inject beans that are available only within UI scope (when the user has the page opened) into classic spring @Component beans. Simple, let's have classes:

@Component
public class A {

    @Inject
    private IB b;
}

@UIScope
@SpringComponent
public class B implements IB {
}

And obviously during startup:

Caused by: java.lang.IllegalStateException: No VaadinSession bound to current thread

What is the normal way how to do it? I understand the whole concept, that beans are initialized on startup when UI scope is not available, but I use common libraries which are implemented in Spring with @Component and I want to implement some of the interfaces, but I can do it only in UI scope and not during startup.

2

There are 2 best solutions below

0
On

Try injecting an aop scoped proxy instead.

For example:

@Scope(value="vaadin-ui", proxyMode=ScopedProxyMode.INTERFACES)
@SpringComponent
public class B implements IB {
}

I think that should work.

0
On

You need to get it from ApplicationContext itself:

@Component
public class A {

      @Autowired
      private ApplicationContext context;

      public B getCurrentB(){
            return context.getBean(B.class);
      }
}

Note that it will throw exception if there is no UI bound to the current thread (normally). In other words, you MUST make sure this method only gets called during a UI request. Any kind of listener in Vaadin should be OK, as long as you're in the same thread with the request.