javaosgideclarative-services

Injecting components in manually created instances


Suppose I have something like this:

@Component(immediate = true)
public class A {}

public class B {
    @Reference
    public void injectA(A a) {...}
}

Is there a way to have A be injected into B if I manually create instances of B? If not, is the only alternative to just use the service registry or is there a go-to pattern?

UPDATE: I can't manually inject an instance of A (without using the service registry) because the code that creates instances of B doesn't have it.


Solution

  • Clearly you can do new B().injectA(new A()). But if you want to manually inject the A instance created by SCR, you need to get that A instance from the service registry which is where SCR makes it available.