美文网首页
TinySpring构建过程Step6-ApplicationC

TinySpring构建过程Step6-ApplicationC

作者: ArthurPapa | 来源:发表于2019-01-19 22:23 被阅读0次

其实BeanFactory已经提供了完整的功能,但是使用起来比较麻烦。现在用ApplicationContext做一个借口封装。

1. ApplicationContext接口

    public interface ApplicationContext extends BeanFactory {
    }

2. AbstractApplicationContext抽象类

    public abstract class AbstractApplicationContext implements ApplicationContext {
        protected AbstractBeanFactory beanFactory;
    
        public AbstractApplicationContext(AbstractBeanFactory beanFactory) {
            this.beanFactory = beanFactory;
        }
    
        public void refresh() throws Exception{
        }
    
        @Override
        public Object getBean(String name) throws Exception {
            return beanFactory.getBean(name);
        }
    }

3. ClassPathXmlApplicationContextxml的ApplicationContext,refesh()用来初始化Bean

    public class ClassPathXmlApplicationContext extends AbstractApplicationContext {
    
        private String configLocation;
    
        public ClassPathXmlApplicationContext(String configLocation) throws Exception {
            this(configLocation, new AutowireCapableBeanFactory());
        }
    
        public ClassPathXmlApplicationContext(String configLocation, AbstractBeanFactory beanFactory) throws Exception {
            super(beanFactory);
            this.configLocation = configLocation;
            refresh();
        }
    
        @Override
        public void refresh() throws Exception {
            XmlBeanDefinitionReader xmlBeanDefinitionReader = new XmlBeanDefinitionReader(new ResourceLoader());
            xmlBeanDefinitionReader.loadBeanDefinitions(configLocation);
            for (Map.Entry<String, BeanDefinition> beanDefinitionEntry : xmlBeanDefinitionReader.getRegistry().entrySet()) {
                beanFactory.registerBeanDefinition(beanDefinitionEntry.getKey(), beanDefinitionEntry.getValue());
            }
        }
    
    }

4. 测试代码,比之前使用更佳简便,封装了实现细节。

    @Test
    public void test() throws Exception {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("tinyioc.xml");
        HelloWorldService helloWorldService = (HelloWorldService) applicationContext.getBean("helloWorldService");
        helloWorldService.helloWorld();
    }

相关文章

网友评论

      本文标题:TinySpring构建过程Step6-ApplicationC

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