Generic way to get Service Reference CQ5

@Reference sometimes fails to get reference out from felix.

To get away with this problem you can use cardinality. Cardinality ensures that if the service reference is not available then your class will not startup.

The other way of getting service reference out of any class in a java file is as below.

This is equivalent of sling.getService in a jsp.

public static <T> T getServiceReference(final Class<T> serviceClass) {
T serviceRef;
/**
* Get the BundleContext associated with the passed class reference.
*/
BundleContext bundleContext = FrameworkUtil.getBundle(serviceClass).getBundleContext();
ServiceReference osgiRef = bundleContext
.getServiceReference(serviceClass.getName());
serviceRef = (T) bundleContext.getService(osgiRef);
return serviceRef;
}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s