0

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 ?

Bourbon_7
  • 161
  • 7
  • Have you read something like the Vogella tutorial - https://www.vogella.com/tutorials/OSGi/article.html ? My understanding is that `immediate=true` starts the service as soon as possible which is not what you want here. You can't use `new` as that doesn't do any sort of injection. The Vogella tutorial talks about getting services from the bundle context or using ServiceTracker. – greg-449 Jul 11 '23 at 12:13
  • Yes, I know I can use the bundle context or ServiceTracker or annotate the `bar` with `@Inject` and then get the service via `ContextInjectionFactory.inject( new Foo(), context )`. I'm new to DS and I'm looking into it, and I was wondering if I could use `@Reference` to get the service in a similar way to `ContextInjectionFactory.inject()`, but it doesn't seem to work! – Bourbon_7 Jul 11 '23 at 13:00

1 Answers1

0

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.

Christian Schneider
  • 19,420
  • 2
  • 39
  • 64