问题
There seem to be 2 ways to get the Configuration Admin service from the OSGi service registry. One by instantiating BundleContext, then getting ServiceReference from that, then ConfigurationAdmin from that:
BundleContext bc = FrameworkUtil.getBundle(ManagedService.class).getBundleContext();
ServiceReference ca = bc.getServiceReference(ConfigurationAdmin.class);
ConfigurationAdmin configAdmin = (ConfigurationAdmin) context.getService(ca);
Another by using Blueprint and simply creating a reference to ConfigurationAdmin, as shown below, then referencing that in a bean:
<reference id="configAdmin" interface="org.osgi.service.cm.ConfigurationAdmin" />
Are these 2 approaches equivalent? Or does the former approach provide anything the latter doesn't? And is there any Blueprint reference documentation that describes what it's doing to instantiate ConfigurationAdmin (can't seem to find any)?
回答1:
These are not "instantiating" a Configuration Admin service. They are ways of getting the service object for the Configuration Admin service from the OSGi service registry. Both ways would return the same service object. The first way uses the low-level OSGi API to interact with the OSGi service registry. The second way uses Blueprint.
Regarding Blueprint, I would instead recommend using Declarative Services for dependency injection in OSGi.
回答2:
Generally you get the same service object with blueprint, DS or the low level API.
The problem though is that the simple approach you used for the low level API is not working well in OSGi. In OSGi services as well as bundles can come and go at any time.
So correct code should always react on a service being removed. You should never hold a service object over a longer time without reacting on the service being removed.
Another thing is that you likely depend on the service you are getting. So you have to cope with the fact that the service might not be there when you start the Activator.
When you scale this up to even just a handful of services offered and consumed by your bundle then it is almost impossible to correctly implement this using the low level API.
So I strongly suggest you use either blueprint OR DS. Recently I try to use DS whenever possible as it can cope with the dynamics of OSGi in the best way. It makes it quite easy to write correct OSGi code.
来源:https://stackoverflow.com/questions/45222221/osgi-configurationadmin-service