theanubhava
theanubhava

Reputation: 576

How to get the instance of an OSGi service in AEM, without using @Reference annotation?

I have a factory service as-

com.adobe.test.MyService

And i have configured it with multiple configurations at its properties. I want to use a particularly configured service instance in any of my class. I can use annotation like-

@Reference("uniqueId=878")
MyService myService

But what if i want to use the sling method like-

com.adobe.test.MyService myService = sling.getService(com.adobe.test.MyService.class);

where and how can i define the unique id for a particular instance of my interest?

Upvotes: 1

Views: 3432

Answers (2)

snaem
snaem

Reputation: 85

Please try this

static <T> T getService(Class<T> serviceClass) {
    BundleContext bContext = FrameworkUtil.getBundle(serviceClass).getBundleContext();
    ServiceReference sr = bContext.getServiceReference(serviceClass.getName());
        return serviceClass.cast(bContext.getService(sr));
}

Then you can call the service

MyService ms = getService(MyService.class);

Upvotes: 0

Oleksandr Tarasenko
Oleksandr Tarasenko

Reputation: 1454

Object sling is an instance of SlingSriptHelper, which has method getServices which accepts a String as a second parameter, which stands for filtering.

Example of such filtering you can find there. Full specification of filter syntax you can find in OSGi specification.

Upvotes: 3

Related Questions