简体   繁体   中英

OSGi - Getting implementation for an interface

Say I have an interface Book in my API bundle and some implementation BookImpl in my implementation bundle. Generally, for singletons, I'd use the service registry to get my implementation. For Book , however, I'd like to create a new instance every time I get the implementation.

What is the normal pattern for doing this in OSGi?

Would I have a service BookCreator with a method createBook that I get from the service registry and use to create my book instances?

That's a good option, yes. You could also consider one of the service injection frameworks, such as declarative services or blueprint. Blueprint allows you to specify a prototype scope, so that each consumer of a 'Book' gets its own instance, which may or may not be unique enough to help with your use case. (DS has something similar.)

However, even the same consumer instance needs to get multiple 'Book's and you use a factory, using one of these frameworks will make your service access more robust.

After thinking long and hard about this issue 2 years ago I found that the proposed solution, a service acting as a factory, is the best solution. The reason is the associated type safety. Declarative services do have a built in possibility with the Component Factory that allows you to create Component Instances its use is just not as easy as a type safe factory. I also considered putting the concept in the framework but also that lacked the easy of a simple factory service.

So yes, your idea is the best solution that I know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM