kaitosenpai
kaitosenpai

Reputation: 1013

OSGI - Choose which bundle to activate from another Component class

I want to develop OSGI storage service so I created an interface called Store. Now, I have two classes that implement this interface.

SqlStorage.java

@Component(immediate = true)
@Service
public class SqlStorage implements Store {
    //some code here
}

MongoStorage.java

@Component(immediate = true)
@Service
public class MongoStorage implements Store {
    //some code here
}

Now, I have another bundle that depends on the Store.

@Component(immediate = true)
@Service
public class StoreManager implements StoreService {
    // how can I select one of the implmentation here
    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
    public Store store;
}

How can the StoreManager choose which implementation of Store to be used?

Suppose, StoreManager has the ability to choose whether to use SQL or MongoDB as a storage.

Is this kind of scenario doable?

Upvotes: 0

Views: 487

Answers (1)

Neil Bartlett
Neil Bartlett

Reputation: 23948

How does your store manager want to decide which implementation of Store to use? As you have currently defined them, the Store implementations are equivalent and equally good answers, and so OSGi will choose one arbitrarily.

If that's not what you want then you need to add service properties to distinguish the Stores. For example:

@Component(property = { "region=NorthAmerica", "language=en_US" })
@Component(property = { "region=Europe", "language=en_GB" })
@Component(property = { "region=Asia", "language=jp" })

Then your store manager can select the store it wants using a target filter. For example if it wants an English-language store (but doesn't care about American vs British English) then it can use the following filter:

@Reference(target = "(language=en*)")

Upvotes: 1

Related Questions