April 3, 2020
Estimated Post Reading Time ~

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 to 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;
}



By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.