How to collect and inject all beans of a given type in Spring XML configuration

前端 未结 3 1241
时光说笑
时光说笑 2020-12-01 08:17

One of the strongest accents of the Spring framework is the Dependency Injection concept. I understand one of the advices behind that is to separate general high-level mecha

3条回答
  •  情深已故
    2020-12-01 08:49

    There's no out-of-the-box facility to do this, no. However, if you want a way of collecting all beans of a given type into a collection, without using an @Autowired list, then it's easy to write a custom FactoryBean to do it for you:

    public class BeanListFactoryBean extends AbstractFactoryBean> {
    
        private Class beanType;
        private @Autowired ListableBeanFactory beanFactory;
    
        @Required
        public void setBeanType(Class beanType) {
            this.beanType = beanType;
        }
    
        @Override
        protected Collection createInstance() throws Exception {
            return beanFactory.getBeansOfType(beanType).values();
        }
    
        @Override
        public Class getObjectType() {
            return Collection.class;
        }    
    }
    

    and then

     
        
           
              
           
        
     
    

    However, this all seems like a lot of effort to avoid putting @Autowired in your original class. It's not much of a violation of SoC, if it is at all - there's no compiltime dependency, and no knowledge of where the options are coming from.

提交回复
热议问题