Looking for an OSGi Design-Pattern
I'm currently facing an interesting problem in my OSGi application.
I'm implementing a configuration service that should retrieve the application's configuration from multiple sources (file, registry or network). The configuration service should read from the sources in a special order until he got a value for the configuration property.First I thought of putting each source in a separate bundle, create a super interface for them and let them provide a declarative service. This would also help to modularize the registry which is required since it is not available on 开发者_Go百科every OS. When the configuration service is asked for a property's value it queries for all source bundles according to the whiteboard pattern and reads the configuration until he got a non-null value. But it does it in a random order.
Does anyone have an idea how to implement a special order in traversing the bundles providing the configuration service?
Best regards
OSGi already has a concept of service ranking. When registering a service, you can provide a value for the property "service.ranking" (org.osgi.framework.Constants.SERVICE_RANKING).
I don't think that this property has any effect on the order in which BundleContext#getServiceReferences() returns available service references (at least the spec doesn't say anything about it) , but you could still use the property value to order the internal collection managed by your "super" config service.
However, to me it is generally a strange idea to let the service implementation itself determine its relative importance. I would rather split the problem in two parts.
- A config service acting as a facacde for
- a collection of config source providers
The second interface would include some characterization concept (e.g. an enum {file, registry, net}
). I would then have the implementation of the first interface (the facade) perform the ordering based on the characteristic of each provider (as the first answer by Chris already suggests).
In general if you need a special order of traversing for a bunch of objects, you just define a (partial) order between your objects. Then, you sort the objects you've got and go through that list.
So, for your problem, when a property's value is needed, you find all the sources, you sort them in a list and finally iterate though it.
精彩评论