The following works on my machine without a problem, I added a few methods to prove the correct injection:
X.java
package org.example;
public interface X {
void method();
}
Y.java
package org.example;
import org.springframework.stereotype.Service;
@Service("Y-Impl")
public class Y implements X {
public void method() {
System.out.println("Y");
}
}
Z.java
package org.example;
import org.springframework.stereotype.Service;
@Service("Z-Impl")
public class Z extends Y implements X {
public void method() {
System.out.println("Z");
}
}
TestClass.java
package org.example;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
@Service
public class TestClass {
private final X x1;
private final X x2;
public TestClass(@Qualifier("Y-Impl") X x1, @Qualifier("Z-Impl") X x2) {
this.x1 = x1;
this.x2 = x2;
}
public void print() {
x1.method();
x2.method();
}
}
AppStartupRunner.java
package org.example;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
@Component
public class AppStartupRunner implements ApplicationRunner {
private final TestClass testClass;
public AppStartupRunner(TestClass testClass) {
this.testClass = testClass;
}
@Override
public void run(ApplicationArguments args) {
testClass.print();
}
}
=> Result:
Y
Z
Edit:
For the sake of completeness here the rest of my test project
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.3.RELEASE</version>
<relativePath/>
</parent>
<groupId>org.example</groupId>
<artifactId>SpringBoot</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
Application.java
package org.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}