Java設計模式——工廠模式——模擬Spring

模擬Spring讀取Properties文件

轉自:http://www.cnblogs.com/shamgod/p/4586971.html

一、目標:讀取配置文件properties文件,獲得類名來生成對象

二、類

1.Movable.java

1
2
3
public interface Movable {
    void run();
}

  

2.Car.java

1
2
3
4
5
6
7
public class Car implements Movable {
 
    public void run() {
        System.out.println("Car running...............");
    }
     
}

  

3.spring.properties

PS:"="兩邊不能有空格

1
vechileType=com.tong.spring.factory.Car

  

4.Test.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Test {
     
    @org.junit.Test
    public void test() {
         
        //讀取properties文件,獲得類名來生成對象
        Properties pros = new Properties();
         
        try {
            //1.讀取要實例化的類名
            pros.load(Test.class.getClassLoader().getResourceAsStream("com/tong/spring/factory/spring.properties"));
            String vechileType = pros.getProperty("vechileType");
             
            //2.利用反射裝載類及用newInstance()實例化類
            Object o = Class.forName(vechileType).newInstance();
            Movable m = (Movable)o;
            m.run();
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

  

5.運行結果:

 

 

6.若改成spring讀取xml文件,則spring配置好後,增加applicationContext.xml

1
2
3
4
5
6
7
8
9
10
11
12
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
 
  <bean id="vehicle" class="com.tong.spring.factory.Car">
  </bean>
 
  <!-- more bean definitions go here -->
 
</beans>

  

7.Test.java改爲如下

1
2
3
4
5
6
7
8
9
10
11
public class Test {
     
    @org.junit.Test
    public void test() {
         
        BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");
        Object o = factory.getBean("vehicle");
        Movable m = (Movable)o;
        m.run();
    }
}

用Jdom模擬Spring

轉自:http://www.cnblogs.com/shamgod/p/4587387.html

 一、概述

1.目標:模擬Spring的Ioc

2.用到的知識點:利用jdom的xpath讀取xml文件,反射

 

二、有如下文件:

1.applicationContext.xml

1
2
3
4
5
<?xml version="1.0" encoding="UTF-8"?>
<beans>
  <bean id="vehicle" class="com.tong.spring.factory.Car">
  </bean>
</beans>

  

2.BeanFactory.java

1
2
3
public interface BeanFactory {
    Object getBean(String id);
}

  

3.ClassPathXmlApplicationContext.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
public class ClassPathXmlApplicationContext implements BeanFactory{
     
    private Map<String, Object> container = new HashMap<String, Object>();
 
    public ClassPathXmlApplicationContext(String fileName) {
         
        //讀取xml文件
        SAXBuilder sb = new SAXBuilder();
        Document doc;
        try {
            //doc = sb.build(fileName);
            //Test.java要改爲BeanFactory factory = new ClassPathXmlApplicationContext("com/tong/spring/factory/applicationContext.xml");
            //否則付出現“java.net.MalformedURLException”
            doc = sb.build(this.getClass().getClassLoader().getResourceAsStream(fileName));
            Element root = doc.getRootElement();
            List list = XPath.selectNodes(root, "/beans/bean");
 
            for (int i = 0; i < list.size(); i++) {
                Element element = (Element) list.get(i);
                String id = element.getAttributeValue("id");
                String clazz = element.getAttributeValue("class");
 
                // 利用反射生成例,然後裝進容器
                Object o = Class.forName(clazz).newInstance();
                container.put(id, o);
            }
        catch (Exception e) {
            e.printStackTrace();
        }
 
    }
 
    @Override
    public Object getBean(String id) {
        return container.get(id);
    }
 
}

  

4.Movable.java

1
2
3
public interface Movable {
    void run();
}

  

5.Car.java

1
2
3
4
5
6
7
public class Car implements Movable {
 
    public void run() {
        System.out.println("Car running...............");
    }
     
}

 

6.Test.java 

 

1
2
3
4
5
6
7
8
9
10
11
12
public class Test {
     
    @org.junit.Test
    public void test() {
         
        //BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");
        BeanFactory factory = new ClassPathXmlApplicationContext("com/tong/spring/factory/applicationContext.xml");
        Object o = factory.getBean("vehicle");
        Movable m = (Movable)o;
        m.run();
    }
}

 

  

 

  

運行結果:

JDOM 2操作XML:http://www.studytrails.com/java/xml/jdom2/java-xml-jdom2-xpath/

package com.studytrails.xml.jdom;
  
import java.io.IOException;
import java.util.List;
 
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.Namespace;
import org.jdom2.filter.Filters;
import org.jdom2.input.SAXBuilder;
import org.jdom2.xpath.XPathExpression;
import org.jdom2.xpath.XPathFactory;
  
public class XPathExample2 {
    private static String xmlSource = "http://feeds.bbci.co.uk/news/technology/rss.xml?edition=int";
  
    public static void main(String[] args) throws JDOMException, IOException {
  
        // read the XML into a JDOM2 document.
        SAXBuilder jdomBuilder = new SAXBuilder();
        Document jdomDocument = jdomBuilder.build(xmlSource);
  
        // use the default implementation
        XPathFactory xFactory = XPathFactory.instance();
        // System.out.println(xFactory.getClass());
  
        // select all links
        XPathExpression<Element> expr = xFactory.compile("//link", Filters.element());
        List<Element> links = expr.evaluate(jdomDocument);
        for (Element linkElement : links) {
            System.out.println(linkElement.getValue());
        }
  
        // select all links in image element
        expr = xFactory.compile("//image/link", Filters.element());
        List<Element> links2 = expr.evaluate(jdomDocument);
        for (Element linkElement : links2) {
            System.out.println(linkElement.getValue());
        }
  
        // get the media namespace
        Namespace media = jdomDocument.getRootElement().getNamespace("media");
        // find all thumbnail elements from the media namespace where the
        // attribute widht has a value > 60
        expr = xFactory.compile("//media:thumbnail[@width>60.00]", Filters.element(), null, media);
        // find the first element in the document and get its attribute named 'url'
        System.out.println(expr.evaluateFirst(jdomDocument).getAttributeValue("url"));
                 
  
        // find the child element of channel whose name is title. find the
        // descendant of item with name title.
        Element firstTitle = xFactory.compile("//channel/child::item/descendant::title", Filters.element()).evaluateFirst(jdomDocument);
        System.out.println(firstTitle.getValue());
  
    }
  
}




發佈了71 篇原創文章 · 獲贊 208 · 訪問量 81萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章