CDI has the feature of Specialization, and I'm looking for that in the Spring world.
Details.
In CDI, the @Specializes annotation allows one to change the behaviour of a bean just by overriding it. This is completely transparent to users of that bean, e.g. if we'd have
public class OneBean {
public String whoAmI() { return "OneBean"; }
}
@Specializes
public class AnotherBean extends OneBean {
@Override
public String whoAmI() { return "AnotherBean"; }
}
we could
public class SomewhereElse {
@Inject
OneBean oneBean; // we know nothing of AnotherBean here!
public void guessWhosThere() {
return oneBean.whoAmI(); // yet it returns "AnotherBean"
}
}
This gets really useful as soon as OneBean is actually used with and without AnotherBean. For example, if OneBean is in one.jar and AnotherBean is in another.jar, we can change the bean's behaviour just by reconfiguring the classpath.
Question. Does something like Specialization also exist in Spring?
I could only find the @Primary annotation, which however has a different semantics: @Primary does not replace one bean, but only marks one of multiple alternatives as the primary one. Especially, as I understood, I could not build a deep inheritance hierarchy as it's possible with @Specializes.
Short answer In Spring 4, this is not possible. Period. Still, in 2016, nothing like this is possible with Spring's obsolete dependency injection model.