How to reference a service in a non-service class?

63 Views Asked by At

As the title suggests, I would like to reference a service in a non-service class, the way I can think of is as follows :

@Component( immediate = true )
public class Foo {
    
    @Reference
    private Bar bar ;
    
}

But Foo seems to be instantiated and references bar when the plugin it's in starts up, if I new Foo(), bar is null.

Is there any way to make Foo not instantiate automatically, but rather I can new it myself and make bar not null ?

In other words, must the Component be created when the plugin starts ?

1

There are 1 best solutions below

0
Christian Schneider On

Use the newest DS spec from OSGi R7 or R8. It allows constructor injection of services. This way you can inject the service also when doing new.