@Specializes in Spring
With Spring boot, you could probably get a similar result by leveraging its auto-configure mechanism, e.g. with a bean condition such as @ConditionalOnMissingBean
:
public class OneBean {
public String whoAmI() { return "OneBean"; }
}
@Configuration
public class OneConfiguration {
@Bean
@ConditionalOnMissingBean
public OneBean getBean() { return new OneBean(); }
}
@Component
public class AnotherBean extends OneBean {
@Override
public String whoAmI() { return "AnotherBean"; }
}
However, you would have to make sure that all configurations are built accordingly if you don't know for sure which ones will be specialized:
public class OneBean {
public String whoAmI() { return "OneBean"; }
}
public class AnotherBean extends OneBean {
@Override
public String whoAmI() { return "AnotherBean"; }
}
public class YetAnotherBean extends AnotherBean {
@Override
public String whoAmI() { return "YetAnotherBean"; }
}
@Configuration
public class OneConfiguration {
@Bean
@ConditionalOnMissingBean
public OneBean getBean() { return new OneBean(); }
}
@Configuration
public class AnotherConfiguration {
@Bean
@ConditionalOnMissingBean
public AnotherBean getBean() { return new AnotherBean(); }
}
@Configuration
public class YetAnotherConfiguration {
@Bean
@ConditionalOnMissingBean
public YetAnotherBean getBean() { return new YetAnotherBean(); }
}
// and so on...
Seems like there is no similar annotation in spring, but you can achive it via @Qualifier.
Beans:
@Resource("oneBean")
public class OneBean {
public String whoAmI() { return "OneBean"; }
}
@Resource("anotherBean")
public class AnotherBean extends OneBean {
@Override
public String whoAmI() { return "AnotherBean"; }
}
SomewhereElse:
public class SomewhereElse {
@Autowired
@Qualifier("anotherBean")
OneBean oneBean;
public void guessWhosThere() {
return oneBean.whoAmI(); // returns "AnotherBean"
}
}
Edited.
Also you can develop your own annotation and use it in BeanPostProcessor, look at spring docs here
OR even better to use CustomAutowireConfigurer, see here
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.