0

I have a list of animals created by Autowiring.

public class UserManagerConfig {
    @Bean
    public Dog getDog(){
        return new Dog("Lucky");
    }

    @Bean Cat getCat(){
        return new Cat("Charles");
    }
}

public class Zoo {

    @Autowired
    private List<Animal> animals;
}

I would like to add a getDogs() that appends more dogs to the autowired list:

    @Bean
    public List<Animal> getDogs(){
        return new ArrayList<>(Arrays.asList(new Dog("Ray"), new Dog("Soos")));
    }

But Spring is not choosing getDogs() while autowiring, it makes a list of beans configured before getDogs() (returning Animal and not List).

Is there a way to tell spring to add this list?

  • You need auto wiring by name. See proposed duplicate. – Strelok Jan 27 '20 at 12:38
  • 1
    Does this answer your question? [How to autowire by name in Spring with annotations?](https://stackoverflow.com/questions/36183624/how-to-autowire-by-name-in-spring-with-annotations) – Strelok Jan 27 '20 at 12:39
  • not really...I can do a hack using Qualifier, but I wonder if there is a better way. – Anton Gellashvili Jan 27 '20 at 12:45
  • 1
    It’s not a hack. If there are 2 beans of same type existing in the context you must choose it by name if you want to use the @Autowire annotation. – Strelok Jan 27 '20 at 12:46
  • Ok.. what if i want to auto-wire all implementations of animal (Components), and add getDogs to create some more dogs and add them to all the components. I'll have to use the answer i stated below.. you think its the best solution? – Anton Gellashvili Jan 27 '20 at 12:52
  • What are you trying to achieve? You want to autowire data classes, or so it seems. That's not what people generally do in Spring. – Christine Jan 27 '20 at 13:06

1 Answers1

0

I was able to make spring to use getDogs() by Autowiring the list to getdogs like this:

public class UserManagerConfig {
    @Bean
    public Dog getDog(){
        return new Dog("Lucky");
    }

    @Bean Cat getCat(){
        return new Cat("Charles");
    }

    @Bean
    public List<Animal> getDogs(List<Animal> animals){
        animals.addAll(new ArrayList<>(Arrays.asList(new Dog("ray"), new Dog("soos"))));
        return animals;
    }
}

And than use @Qualifier:

public class Zoo {

    @Autowired
    @Qualifier("getDogs")
    private List<Animal> animals;
}

Is there a better solution?

JuanMoreno
  • 2,498
  • 1
  • 25
  • 34