Step 1-: Define the Interface and Implementations
Animal.java (Interface)
public interface Animal {
void makeSound();
}Cat.java (Implementation 1)
import org.apache.sling.api.resource.Resource;
public class Cat implements Animal {
@9944223
public void makeSound() {
System.out.println("Meow");
}
}Dog.java (Implementation 2)
import org.apache.sling.api.resource.Resource;
public class Dog implements Animal {
@9944223
public void makeSound() {
System.out.println("Woof");
}
}Step 2-: Use Dependency Injection in Your Sling Model.
To ensure that you get the Dog implementation specifically, you should use the @3214626 annotation and mention target instance which you want to call.
import org.apache.sling.models.annotations.Model;
import org.osgi.service.component.annotations.Reference;
@Model(adaptables = Resource.class)
public class MySlingModel {
@3214626(target = "(instance=dog)")
private Animal animal;
public void makeAnimalSound() {
animal.makeSound();
}
}