How do I access an OSGI service from any class? | Community
Skip to main content
jayv25585659
Level 8
April 12, 2019
Solved

How do I access an OSGI service from any class?

  • April 12, 2019
  • 3 replies
  • 4992 views

I have a service (located inside /core/src/java/com/myhost/core/services) and service implementation (located /core/src/java/com/myhost/core/services/impl).

I have an existing class (located inside /core/src/java/com/myhost/core/impl/view/components) that extends com.adobe.cq.sightly.WCMUsePojo. Using getSlingScripterHelper, this class can acceess the service I mentioned above.

I'm trying to access the service without using WCMUsePojo. How can I do it?

Thanks!

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.
Best answer by BrijeshYadav

What exactly is your use case not to use WCMUsePojo class?

I would recommend to use Sling Model instead of WCMUsePojo.

Adobe Experience Manager Help | Creating Adobe Experience Manager 6.3 Sling Model Components

Sling models and WCMUsePojo

AEM Concepts | AEM Tutorial | Know Adobe CQ better: Sling models and WCMUsePojo

3 replies

BrijeshYadav
BrijeshYadavAccepted solution
Level 5
April 12, 2019

What exactly is your use case not to use WCMUsePojo class?

I would recommend to use Sling Model instead of WCMUsePojo.

Adobe Experience Manager Help | Creating Adobe Experience Manager 6.3 Sling Model Components

Sling models and WCMUsePojo

AEM Concepts | AEM Tutorial | Know Adobe CQ better: Sling models and WCMUsePojo

smacdonald2008
Level 10
April 18, 2019

When you are in a SLing Model - you can reference another OSGi Serice by using:

@Inject

MyService service ;

This works nicely.

joerghoh
Adobe Employee
Adobe Employee
April 19, 2019

Technically speaking, there is a chance to get the bundlecontext of the bundle, which the class is part of. And from there get references to other services. But that's not easy to implement, and additionally this reference is not managed, thus you need to take care of the lifecycle events of the surrouding services. Probably not what you want.

Instead I would suggest that you convert your custom class into an OSGI service (or Sling model), because then the full tooling is available, and the frameworks takes care about wiring and all other lifecycle events and situations. In my coding experience I also often thought of simple utility classes, and ended up converting them into OSGI services, because then it was much easier to access the services available in the system.