How can I acess my own Service with the ComponentAccessor?

I usually access my Services via constructor injection, but I have a use case where I would rather like to inject it via the ComponentAccessor (I know it should be used rarely).

My Service Interface and implementation look like this:

@Named
public class MyServiceImpl implements MyService{

    @ComponentImport
    private final ActiveObjects ao;


    @Inject
    public MyServiceImpl(ActiveObjects ao) {
        this.ao = checkNotNull(ao);
    }
...
}	

public interface MyService {
...
}

And I’m trying to inject it like this, but always get a null object:

ConfigService configService= ComponentAccessor.getOSGiComponentInstanceOfType(MyService.class);

With constructer injection it works though. Can anyone give me a hint?

Hello Caroline,

As long as there’s some kind of dependency injection (for JIRA components), maybe you can try to inject Spring’s ApplicationContext, and then use getBean as needed. I found that this works for our use case.

Something along the lines of:

@Named
public class Foo {

    @ComponentImport
    private final ApplicationContext applicationContext;


    @Inject
    public Foo(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }
    
    public bar() {
        // applicationContext.getBean(MyService.class)
    }
}

It doesn’t use ComponentAccessor, but it does indeed provide a way of getting an internal component by means of something different than pure dependency injection.

1 Like

Thank you, that’s a good solution.