多接口实现 - AEM/CQ - OSGi

Multiple Interface Implementations - AEM/CQ - OSGi

有一个服务接口HelloService,这是由2个服务实现实现的

HelloService 接口

public interface HelloService {
    public String getRepositoryName();
}

HelloServiceImpl1 实现

@Service
@Component(metatype = false)
public class HelloServiceImpl1 implements HelloService {

    @Reference
    private SlingRepository repository;

    public String getRepositoryName() {
        return repository.getDescriptor(Repository.REP_NAME_DESC);
    }
}

HelloServiceimpl2 实现

@Service
@Component(metatype = false)
public class HelloServiceImpl2 implements HelloService {

    public String getRepositoryName() {
        return "Response from HelloServiceImpl2";
    }
}

现在开始使用我们使用的服务

@Reference
HelloService helloService;

在所需方法中,调用方式为

helloService.getRepositoryName();

我总是收到 HelloServiceImpl1 的回复。检查了 AEM API 中的另一个示例,SlingRepositoryAbstractSlingRepositoryAbstractSlingRepository2 扩展,如何在内部选择实现,因为在使用时我们仅指定 @Reference SlingRepository repository;

这在 AEM OSGi 中是如何处理的?


根据响应更新

检查了语法,以下是观察结果

要使用服务排名,请使用跟随服务实施

@Properties({
    @Property(name = Constants.SERVICE_RANKING, intValue = 100)
})

对于这种消费没有变化,更高的服务排名实现被拾取,控制由提供者

@Reference
HelloService helloService;

要使用目标过滤器,请使用以下注释指定属性

@Properties({
   @Property(name="type", value="Custom")
})

基于filter消费时,指定target,控制在consumer

 @Reference (target="(type=Custom)")
 HelloService helloService;

如果同时使用服务排名和过滤器,过滤器优先。

这与声明服务如何连接 @Reference 有关。来自规范:

If the reference has a unary cardinality and there is more than one target service for the reference, then the bound service must be the target service with the highest service ranking as specified by the service.ranking property.

If there are multiple target services with the same service ranking, then the bound service must be the target service with the highest service ranking and the lowest service id as specified by the service.id property.

即,它取决于组件的"Service Ranking"。如果没有指定这个排名,那么你可以有任何实现(你通常会得到最旧的服务)。如果您想针对特定实现,可以使用过滤器。