美文网首页
TintySpring构建过程 Step4-属性注入可配置化

TintySpring构建过程 Step4-属性注入可配置化

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

    在这第四步我们需要做的是将我们在第三步的基础上,我们将初始化对象所需要的属性值写在外部xml文件中,这样我们在配置bean的过程中就能够通过外部xml文件来配置,做到配置与编码进一步解耦。xml配置是spring的一个很棒的做法,我们在使用容器的时候可以在不侵入我们业务代码的情况下,做到进一步的容器化,将我们要生成的Bean也作为配置文件的一部分集成在Spring中。这也是为什么Spring能够很方便的集成其他的框架的原因所在,通过xml这薄薄的一层可以对其他框架做到很棒的结合,真尼玛厉害,每次看都有新感受!

    以下是实现过程:


    分析:我们需要从xml文件中读取相应的属性,那么首先我们需要将文件读入内存,然后解析里面的xml内容。解析xml我们可以直接用javax.xml.*包。但是对于文件的读取,我们这里做进一步的考虑,是否可以对所有的IO做统一的封装。事实上,Spring就是这么做的。

    1. IO操作的封装。Spring中将所有的资源抽象为ResourceResource有一个getInputStream()方法获取输入流。

       public interface Resource {
           InputStream getInputStream() throws IOException;
       }
      

      这里我们添加一个UrlResource来表示所有可以表示成一个Url的资源,我们的Xml文件也可以用这个资源来表示。

       public class UrlResource implements Resource {
           //通过构造函数初始化后我们希望它是一个
           //常量,不需要改变,作为这个对象本身的属性
           //所以这个类生成的对象是对一个资源的描述
           private final URL url;
       
           public UrlResource(URL url) {
               this.url = url;
           }
       
           /**
            * 从url中获取inputstream
            * 这是Resource的统一接口均会返回InputStream
            * @return
            * @throws IOException
            */
           @Override
           public InputStream getInputStream() throws IOException {
               URLConnection urlConnection = url.openConnection();
               urlConnection.connect();
               return urlConnection.getInputStream();
           }
       }
      

      在我们的IO包里面,之后可能会添加其他的类型的Resource,所以对于Resource的访问,我们可以添加一个统一访问的接口,方便外部访问而不用关心具体是同那个Resource对象实现的。这里我们添加一个ResourceLoader:

       /**
        * Io对外部的接口,
        *
        * Created by AL on 2017-02-18.
        */
       public class ResourceLoader {
       
           /**
            * 外部调用getResource获取相应的Resource
            * 然后外部再调用Resource.getInputStream()
            * 获取到文件的输入流
            * @param location
            * @return
            */
           public Resource getResource(String location){
               URL resource = this.getClass().getClassLoader().getResource(location);
               return new UrlResource(resource);
           }
       }
      

    现在我们测试一下我们的IO接口是否正常工作:

        @Test
            public void test() throws IOException {
                ResourceLoader resourceLoader = new ResourceLoader();
                Resource resource = resourceLoader.getResource("tinyioc.xml");
                InputStream inputStream = resource.getInputStream();
                Assert.assertNotNull(inputStream);
            }
    
    1. 我们已经实现了从url地址获取输入流,那么剩下的工作就是要对获取到的数据进行解析以及赋值给BeanDefinition
      BeanDefinitionReader

       /**
        * 用来从配置文件中获取相应的BeanDefinition的属性
        * Created by AL on 2017-02-18.
        */
       public interface BeanDefinitionReader {
           /**
            * 根据xml的location加载bean
            * @param location
            * @throws Exception
            */
           void loadBeanDefinitions(String location) throws Exception;
       }
      

    AbstractBeanDefinitionReader

        /**
         * Reader做两件事
         * 1. 从XML中读取信息到BeanDefinition,并保存
         * 2. 外界能够从它这里获取需要的BeanDefinition
         * Created by AL on 2017-02-18.
         */
        public abstract class AbstractBeanDefinitionReader implements BeanDefinitionReader{
            private Map<String,BeanDefinition> register;
            public ResourceLoader resourceLoader;
        
            public AbstractBeanDefinitionReader( ResourceLoader resourceLoader) {
                this.register = new HashMap<String, BeanDefinition>();
                this.resourceLoader = resourceLoader;
            }
        
            public Map<String, BeanDefinition> getRegister() {
                return register;
            }
        
            public ResourceLoader getResourceLoader() {
                return resourceLoader;
            }
        }
    

    XmlBeanDefinitionReader

        /**
         * 用来具体解析Xml文件完成AbstractBeanDefinitionReader的任务
         * Created by AL on 2017-02-18.
         */
        public class XmlBeanDefinitionReader extends AbstractBeanDefinitionReader {
        
            public XmlBeanDefinitionReader(ResourceLoader resourceLoader) {
                super(resourceLoader);
            }
        
        
            @Override
            public void loadBeanDefinitions(String location) throws Exception {
                InputStream inputStream = getResourceLoader().getResource(location).getInputStream();
                doLoadBeanDefinitions(inputStream);
            }
        
            /**
             * 加载所有的Bean
             * @param inputStream
             * @throws Exception
             */
            protected void doLoadBeanDefinitions(InputStream inputStream) throws Exception {
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder docBuilder = factory.newDocumentBuilder();
                Document doc = docBuilder.parse(inputStream);
                // 解析bean
                registerBeanDefinitions(doc);
                inputStream.close();
            }
        
            /**
             * 获取根节点
             * @param doc
             */
            public void registerBeanDefinitions(Document doc) {
                Element root = doc.getDocumentElement();
                parseBeanDefinitions(root);
            }
        
            /**
             * 遍历第一层子节点
             * 这里暂时只有Bean
             * @param root
             */
            protected void parseBeanDefinitions(Element root) {
                NodeList nl = root.getChildNodes();
                for (int i = 0; i < nl.getLength(); i++) {
                    Node node = nl.item(i);
                    if (node instanceof Element) {
                        Element ele = (Element) node;
                        processBeanDefinition(ele);
                    }
                }
            }
        
            /**
             * 对Bean节点进行解析并获取BeanDefinition
             * @param ele
             */
            protected void processBeanDefinition(Element ele) {
                String name = ele.getAttribute("name");
                String className = ele.getAttribute("class");
                BeanDefinition beanDefinition = new BeanDefinition();
                processProperty(ele,beanDefinition);
                beanDefinition.setClassName(className);
                getRegister().put(name, beanDefinition);
            }
        
            /**
             * 解析Bean节点内部属性值
             * @param ele
             * @param beanDefinition
             */
            private void processProperty(Element ele,BeanDefinition beanDefinition) {
                NodeList propertyNode = ele.getElementsByTagName("property");
                for (int i = 0; i < propertyNode.getLength(); i++) {
                    Node node = propertyNode.item(i);
                    if (node instanceof Element) {
                        Element propertyEle = (Element) node;
                        String name = propertyEle.getAttribute("name");
                        String value = propertyEle.getAttribute("value");
                        beanDefinition.getPropertyValues().addPropertyValue(new PropertyValue(name,value));
                    }
                }
            }
        }
    

    当然我们得添加一个xml配置文件

        <?xml version="1.0" encoding="UTF-8"?>
        <beans xmlns="http://www.springframework.org/schema/beans"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
               xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
               xsi:schemaLocation="
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
        
        
            <bean name="helloWorldService" class="com.arthur.HelloService">
                <property name="name" value="arthur"></property>
                <property name="age" value="20"></property>
                <property name="favouriteFood" value="火鸡面"></property>
            </bean>
        </beans>
    

    添加一个xml解析测试

        @Test
        public void test() throws Exception {
            XmlBeanDefinitionReader xmlBeanDefinitionReader = new XmlBeanDefinitionReader(new ResourceLoader());
            xmlBeanDefinitionReader.loadBeanDefinitions("tinyioc.xml");
            Map<String, BeanDefinition> registry = xmlBeanDefinitionReader.getRegister();
            Assert.assertTrue(registry.size() > 0);
        }
    

    注意:添加配置文件的时候,可直接在test目录下建立resources文件夹,下面存放你的xml文件。但是我们需要把他设置成资源文件夹,方能放在classpath下。具体操作如下图:[图片上传失败...(image-5758a8-1547907682458)]

    1. 测试一下属性注入

       @Test
           public void test() throws Exception {
               //读取配置文件
               XmlBeanDefinitionReader xmlBeanDefinitionReader = new XmlBeanDefinitionReader(new ResourceLoader());
               xmlBeanDefinitionReader.loadBeanDefinitions("tinyioc.xml");
       
               //初始化Bean并注册Bean
               BeanFactory beanFactory = new AutowireCapableBeanFactory();
               for(Map.Entry<String,BeanDefinition> beanDefinitionEntry:xmlBeanDefinitionReader.getRegister().entrySet()){
                   beanFactory.registerBeanDefinition(beanDefinitionEntry.getKey(),beanDefinitionEntry.getValue());
               }
       
               HelloService helloService = (HelloService) beanFactory.getBean("helloWorldService");
               helloService.hello();
               helloService.instroduce();
           }
      

    这里注意一点,此处尚未实现非String属性的注入,只是打通的从属性文件读取属性注入。在后续过程中会一一实现。

    相关文章

      网友评论

          本文标题:TintySpring构建过程 Step4-属性注入可配置化

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