0

I am using Vaadin 21 in Apache Karaf, an Osgi container. What i want to do :

  • Create a vaadin Component, annotates it with @Component(scope=ScopeService.PROTOTYPE)

  • In the View with the @Route, the Vaadin doc says that we cannot use injection dependency to get the Osgi Component reference

  • To get the reference, the doc says to use :

    ServiceReference<MyComponent> reference = ctx.getServiceReference(MyService.class);
    MyComponent myComponent = ctx.getService(reference);```
    
    
  • I have a problem when i refresh my screen, the instance of MyComponent stays the same

  • To avoid that, i found an alternative :

        ServiceReference<MyComponent> reference = ctx.getServiceReference(MyComponent.class);
        ServiceObjects<MyComponent> res = ctx.getServiceObjects(reference);
        MyComponent myComponent = res.getService();```
    
    
    
    

Has anyone got a better way to get my Prototype vaadin and osgi component Reference ? Here is my code (from base-starter-flow-osgi) :

public class MainView extends VerticalLayout {

    public MainView() {
        
        BundleContext ctx = FrameworkUtil.getBundle(MyComponent.class).getBundleContext();
        ServiceReference<MyComponent> reference = ctx.getServiceReference(MyComponent.class);
        ServiceObjects<MyComponent> res = ctx.getServiceObjects(reference);
        prestas = res.getService();

        add(myComponent);
    }
}
@Component(service=MyComponent.class, scope=ServiceScope.PROTOTYPE)
public class MyComponent extends Div{
    private static final long serialVersionUID = -8573895829405499446L;

    @Override
    protected void onAttach(AttachEvent attachEvent) {
        super.onAttach(attachEvent);
        add(new Span("Hello World!"));
    }
    
}
kevin
  • 1
  • 1) What's the benefit of using prototype scope over just creating a `new` Component instance in your case? 2) What is the problem with your alternative solution (why are you searching for a "better" way)? – ollitietavainen Dec 03 '21 at 10:59
  • @ollitietavainen thanks for your reply 1) i'd like to use full osgi potential with `@Component` that handles instances lifecycle, dependencies injection, etc. for example, if MyComponent uses some services, here, i just annotates with `Reference` and use bundle context to get MyComponent reference, initialized with its service instances. 2) it seems a litlle complicated or at least verbose to get a component instance, that's why we hesitated using, like you said, new instance. But we're in an osgi environnement so we're looking for a lighter way, more readable, to improve our code – kevin Dec 22 '21 at 13:35
  • Maybe you could update your MyComponent example to include a service injection if that's your use case (try to be specific about what you're asking). And in my humble opinion, injection is always less readable than direct instantiation. – ollitietavainen Dec 22 '21 at 13:43

0 Answers0