編碼剖析Spring管理Bean的原理

來源:互聯網
上載者:User

標籤:www.   put   amp   fine   一個   pre   匯入   get   junit   

在Spring的第一個案例中,我們已經知道了怎麼將bean交給Spring容器進行管理,並且明白了怎麼從Spring容器中擷取bean。那我們就有一個疑問了:Spring是如何建立並管理bean的呢?現在我們就來編碼剖析Spring管理Bean的原理。
本文是在Spring的第一個案例的基礎上展開的。
我們要使用dom4j讀取Sping的設定檔——beans.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"    xsi:schemaLocation="http://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans.xsd">    <bean id="personService" class="cn.itcast.service.impl.PersonServiceBean"></bean></beans>

那麼就需要將dom4j所需的jar包匯入該項目中。dom4j所需的jar包為:

  • dom4j-1.6.1.jar
  • jaxen-1.1-beta-6.jar

dom4j讀取到諸如

<bean id="personService" class="cn.itcast.service.impl.PersonServiceBean"></bean>

這樣的內容時,務必需要將讀取到的bean的資訊存到一個JavaBean對象中。於是我們可在junit.test包下建立這樣一個JavaBean——BeanDefinition.java,其代碼為:

/** * 將讀取到的bean的資訊存到一個JavaBean對象中 * */public class BeanDefinition {    private String id;    private String className;    public BeanDefinition(String id, String className) {        this.id = id;        this.className = className;    }    public String getId() {        return id;    }    public void setId(String id) {        this.id = id;    }    public String getClassName() {        return className;    }    public void setClassName(String className) {        this.className = className;    }}

接下來我們就建立一個傳智播客版的Spring容器來類比Spring容器。在junit.test下建立一個類——ItcastClassPathXMLApplicationContext.java,其代碼如下:

/** * 傳智播客版Spring容器 * */public class ItcastClassPathXMLApplicationContext {    private List<BeanDefinition> beanDefines = new ArrayList<BeanDefinition>();    private Map<String, Object> sigletons = new HashMap<String, Object>();    public ItcastClassPathXMLApplicationContext(String filename) {        this.readXML(filename);        this.instanceBeans();    }    /**     * 完成bean的執行個體化     */    private void instanceBeans() {        for (BeanDefinition beanDefinition : beanDefines) {            try {                if (beanDefinition.getClassName() != null && !"".equals(beanDefinition.getClassName().trim())) {                    sigletons.put(beanDefinition.getId(), Class.forName(beanDefinition.getClassName()).newInstance());                }            } catch (Exception e) {                e.printStackTrace();            }        }    }    /**     * 讀取XML設定檔     * @param filename     */    private void readXML(String filename) {        SAXReader saxReader = new SAXReader();        Document document = null;        try {            URL xmlpath = this.getClass().getClassLoader().getResource(filename);            document = saxReader.read(xmlpath);            Map<String, String> nsMap = new HashMap<String, String>();            nsMap.put("ns", "http://www.springframework.org/schema/beans"); // 加入命名空間            XPath xsub = document.createXPath("//ns:beans/ns:bean"); // 建立beans/bean查詢路徑            xsub.setNamespaceURIs(nsMap); // 設定命名空間            List<Element> beans = xsub.selectNodes(document); // 擷取文檔下所有bean節點            for (Element element : beans) {                String id = element.attributeValue("id"); // 擷取id屬性值                String clazz = element.attributeValue("class"); // 擷取class屬性值                BeanDefinition beanDefine = new BeanDefinition(id, clazz);                beanDefines.add(beanDefine);            }        } catch (Exception e) {            e.printStackTrace();        }    }    /**     * 擷取bean執行個體     * @param beanName     * @return     */    public Object getBean(String beanName) {        return this.sigletons.get(beanName);    }}

這樣,傳智播客版的Spring容器就建立出來了。接下來我們就要測試傳智播客版的Spring容器是否能夠取得bean執行個體,只須修改SpringTest類的代碼為:

public class SpringTest {    @Test    public void test() {        // ApplicationContext是介面        // ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); // 執行個體化Spring容器        // PersonService personService = (PersonService) ctx.getBean("personService"); // 從Spring容器取得bean        // personService.save();        ItcastClassPathXMLApplicationContext ctx = new ItcastClassPathXMLApplicationContext("beans.xml"); // 執行個體化Spring容器        PersonService personService = (PersonService) ctx.getBean("personService"); // 從Spring容器取得bean        personService.save();    }}

測試test()方法,Eclipse控制台列印如下:

通過編寫代碼剖析Spring管理Bean的原理,我們就能深刻理解Spring內部到底是如何建立並管理bean執行個體的.

 

編碼剖析Spring管理Bean的原理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.