0

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.

Karl S.
  • 345
  • 1
  • 9
  • 1
    Sorry if I'm missing something obvious but... if you want to inject an instance of A into B then just call the `injectA` method. – Neil Bartlett Jan 10 '19 at 09:57
  • @NeilBartlett thanks for the suggestion, I've updated my question. – Karl S. Jan 10 '19 at 10:15
  • The question is still not clear, sorry. You want to inject an A into a B but you don't have any means to create an A? And you don't want to go to the service registry to get an A? Is this test code, maybe you are looking for a way to create a mock object to inject? – Neil Bartlett Jan 10 '19 at 13:09
  • 1
    Clearly you can do `new B().injectA(new A())`. But if you want to 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. – BJ Hargrave Jan 10 '19 at 13:24
  • @BJHargrave That's what I wanted to know, i.e. if you could have the instance created by SCR automatically injected or if I had to explicitly get it from the registry. I should have made it clearer in the question. If you make your comment an answer I'll be happy to accept it. – Karl S. Jan 10 '19 at 20:21

1 Answers1

1

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.

BJ Hargrave
  • 9,324
  • 1
  • 19
  • 27