Search code examples
javaspring-bootspring-annotations

Autowired bean based on annotation value type


I have the following classes:

public abstract class Animal {
    public abstract void call();
}

public class Dog extends Animal {
    @Override
    public void call() {
        System.out.println("Dog was called");
    }
}

public class Cat extends Animal {
    @Override
    public void call() {
        System.out.println("Cat was called");
    }
}

public @interface AnimalAnnotation {
    AnimalType value() default AnimalType.DOG;
}

public enum AnimalType {
    DOG,
    CAT
}

In a Configuration class I am creating a bean for the two type of Animal inheritors:

@Configuration
public class AnimalConfiguration {

    @Bean
    public Animal initDog() {
       return new Dog();
    }
    
    @Bean
    public Animal initCat() {
       return new Cat();
    }
}

My intention here is to autowired a bean with dynamic type as it follows:

public class Main {
    @Autowired
    @AnimalAnnotation(AnimalType.CAT)
    private Animal animal; // the instance should be the Cat one
    public void perform() {
        animal.call(); // In the console we should see "Cat was called".
    }
}

This is a example code which describes my intention, which it could be wrong. Can be this be implemented and what is the correct approach?


Solution

  • How about using a @Qualifier? That may work. You would have to give your beans a name like

    @Bean("cat")
    public Animal initCat() {
        return new Cat();
    }
    

    and then when autowiring you would have:

    @Autowired
    @Qualifier("cat")
    private Animal animal;