Search code examples
javaosgiaem

AEM 6.5 @Reference(target = "(component.name=componentName)") Not working


I am trying to inject an AEM component using the target property of the @Reference annotation.

This is the component that I am trying to inject.

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

}

This is the component that uses it is:

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
}

This is the test I am running:

@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
    }
}

When I run the test, I am getting this error: org.apache.sling.testing.mock.osgi.ReferenceViolationException: Unable to inject mandatory reference 'myInterceptor' for class com.test.anotherComponent : no matching services were found.

If I reference the component using @Reference without the target property, the test works. Unfortunately, I have more than one interceptor and the component.name property let me differentiate them.

Any ideas on why this is failing?


Solution

  • When you are registering a service you need to pass additional config to specify target name. In your case something like:

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