【问题标题】:AEM 6.5 @Reference(target = "(component.name=componentName)") Not workingAEM 6.5 @Reference(target = "(component.name=componentName)") 不工作
【发布时间】:2021-09-03 15:07:33
【问题描述】:

我正在尝试使用 @Reference 注释的 target 属性注入 AEM 组件。

这是我要注入的组件。

import org.osgi.service.component.annotations.Component;
import okhttp3.Interceptor;


@Component(immediate = true, name = "myInterceptorComponent", service = {Interceptor.class})
public class myInterceptor implements Interceptor {

  public static final String COMPONENT_NAME = "myInterceptorComponent";
    
  //... some implementation

}

这是使用它的组件是:

import okhttp3.Interceptor;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;

@Component(immediate = true)
public final class anotherComponent {

  @Reference(target = "(component.name=myInterceptorComponent)")
  private Interceptor myInterceptor;
  
  //... another implementation
}

这是我正在运行的测试:

@ExtendWith({AemContextExtension.class})
class anotherComponent Test {
    private final AemContext context = AppAemContext.newAemContext();

    @BeforeEach
    public void setUp() {
        this.context.registerInjectActivateService(myInterceptor.class);
        this.context.registerInjectActivateService(anotherComponent.class);
    }

    @Test
    void testMethod(){
        //Test implementation
    }
}

当我运行测试时,我收到了这个错误: org.apache.sling.testing.mock.osgi.ReferenceViolationException: Unable to inject mandatory reference 'myInterceptor' for class com.test.anotherComponent : no matching services were found.

如果我使用 @Reference 引用组件而没有 target 属性,则测试有效。不幸的是,我有不止一个拦截器,component.name 属性让我可以区分它们。

关于为什么失败的任何想法?

【问题讨论】:

    标签: java osgi aem


    【解决方案1】:

    当您注册服务时,您需要传递额外的配置来指定目标名称。 在你的情况下是这样的:

    this.context.registerInjectActivateService(new MyInterceptor(), Collections.singletonMap("component.name", "myInterceptorComponent"));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-06
      • 1970-01-01
      • 1970-01-01
      • 2018-06-13
      • 1970-01-01
      相关资源
      最近更新 更多