Search code examples
springdependency-injectionautowiredqualifiers

Spring: Qualifying different types with the same name


I have two classes that I want to autowire using spring

@Component
public class Restaurant {
    @Autowired
    @Qualifier("HighClass")
    private CoffeeMaker coffeeMaker;
}

and:

public class CappuccinoMaker implements CoffeeMaker{
    @Autowired
    @Qualifier("HighClass")
    int numOfSpoons;
}

Then injecting:

@Bean(name="HighClass")
@Scope("prototype")
public CoffeeMaker HighClassCoffeeMakerGenerator() {
    return new CappuccinoMaker();
}
@Bean(name="HighClass")
public int getNumOfSpoons() {
    return 3;
}

I'd like to qualify both the int and the CoffeeMaker with "HighClass". In Guice it is possible to annotate different types with the same annotation and inject them correctly.

It seems like in spring this is not allowed. When I try injecting the fields I get an error that the required bean was not found. Did I miss anything?


Solution

  • Bean name in Spring is unique. Use @Profile in order to pick a bean from several competing variants.