Autowire reference beans into list by type

后端 未结 2 563
花落未央
花落未央 2020-11-28 09:43

I have one class that has a list of objects of Daemon type.

class Xyz {    
    List daemons;
}

My spring config

2条回答
  •  离开以前
    2020-11-28 10:10

    It should work like this (remove the ArrayList bean from your XML):

    public Class Xyz {    
    
        private List daemons;
    
        @Autowired
        public void setDaemons(List daemons){
            this.daemons = daemons;
        }
    
    }
    

    I don't think there's a way to do this in XML.


    See: 3.9.2. @Autowired and @Inject:

    It is also possible to provide all beans of a particular type from the ApplicationContext by adding the annotation to a field or method that expects an array of that type:

    public class MovieRecommender {
    
      @Autowired
      private MovieCatalog[] movieCatalogs;
    
      // ...
    }
    

    The same applies for typed collections:

    public class MovieRecommender {
    
      private Set movieCatalogs;
    
      @Autowired
      // or if you don't want a setter, annotate the field
      public void setMovieCatalogs(Set movieCatalogs) {
          this.movieCatalogs = movieCatalogs;
      }
    
      // ...
    }
    

    BTW, as of Spring 4.x, these lists can be ordered automatically using the @Ordered mechanism.

提交回复
热议问题