美文网首页
Spring IOC

Spring IOC

作者: 传葱 | 来源:发表于2019-03-25 13:21 被阅读0次

    Spring IOC容器

    • BeanFactory 用于在比较轻量级的应用中
    • ApplicationContext 一般推荐使用
    public static void main(String[] args) {
          XmlBeanFactory factory = new XmlBeanFactory
                                 (new ClassPathResource("Beans.xml"));
          HelloWorld obj = (HelloWorld) factory.getBean("helloWorld");
          obj.getMessage();
       }
    

    1.通过配置文件构建Factory,或者ApplicationContext,创建并且初始化所有的对象
    2。使用getBean方法获取需要的对象,

    protected Object getSingleton(String beanName, boolean allowEarlyReference) {
            Object singletonObject = this.singletonObjects.get(beanName);
            if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
                synchronized (this.singletonObjects) {
                    singletonObject = this.earlySingletonObjects.get(beanName);
                    if (singletonObject == null && allowEarlyReference) {
                        ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
                        if (singletonFactory != null) {
                            singletonObject = singletonFactory.getObject();
                            this.earlySingletonObjects.put(beanName, singletonObject);
                            this.singletonFactories.remove(beanName);
                        }
                    }
                }
            }
            return (singletonObject != NULL_OBJECT ? singletonObject : null);
        }
    
    • 获得单例对象
    /**
         * Register the bean definitions contained in the given DOM document.
         * Called by {@code loadBeanDefinitions}.
         * <p>Creates a new instance of the parser class and invokes
         * {@code registerBeanDefinitions} on it.
         * @param doc the DOM document
         * @param resource the resource descriptor (for context information)
         * @return the number of bean definitions found
         * @throws BeanDefinitionStoreException in case of parsing errors
         * @see #loadBeanDefinitions
         * @see #setDocumentReaderClass
         * @see BeanDefinitionDocumentReader#registerBeanDefinitions
         */
        public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
            BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
            int countBefore = getRegistry().getBeanDefinitionCount();
            documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
            return getRegistry().getBeanDefinitionCount() - countBefore;
        }
    

    相关文章

      网友评论

          本文标题:Spring IOC

          本文链接:https://www.haomeiwen.com/subject/vcpvvqtx.html