Optional Spring bean references

后端 未结 5 2097
逝去的感伤
逝去的感伤 2020-12-03 17:22

In my application I am using ContextLoaderListener to load context files from many jars using:


    contextConfigLocat         


        
5条回答
  •  独厮守ぢ
    2020-12-03 17:31

    There's no built-in mechanism for this. However, you could write a pretty trivial FactoryBean implementation to do this for you, something like this:

    public class OptionalFactoryBean extends AbstractFactoryBean implements BeanNameAware {
    
        private String beanName;
    
        @Override
        public void setBeanName(String beanName) {
            this.beanName = BeanFactoryUtils.originalBeanName(beanName);
    
        }
    
        @Override
        protected Object createInstance() throws Exception {
            if (getBeanFactory().containsBean(beanName)) {
                return getBeanFactory().getBean(beanName);
            } else {
                return null;
            }
        }
    
        @Override
        public Class getObjectType() {
            return null;
        }
    }
    
    
    

    You can then use it like this:

    
            
        
           
        
        
           
        
    
    

    提交回复
    热议问题