我想开发OSGI存储服务,所以我创建了一个名为Store
的接口(interface)。现在,我有两个实现此接口(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
}
现在,我有另一个依赖于 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;
}
StoreManager
如何选择要使用的 Store
实现?
假设StoreManager
能够选择使用SQL还是MongoDB作为存储。
这种场景可行吗?
最佳答案
您的商店经理希望如何决定使用哪种商店实现?正如您当前定义的那样,Store 实现是等效的并且同样是好的答案,因此 OSGi 将任意选择一个。
如果这不是您想要的,那么您需要添加服务属性来区分商店。例如:
@Component(property = { "region=NorthAmerica", "language=en_US" })
@Component(property = { "region=Europe", "language=en_GB" })
@Component(property = { "region=Asia", "language=jp" })
然后您的商店经理可以使用目标过滤器选择所需的商店。例如,如果它想要一个英语商店(但不关心美式英语和英式英语),那么它可以使用以下过滤器:
@Reference(target = "(language=en*)")
关于java - OSGI - 从另一个组件类中选择要激活的包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45582350/