Java程式員從笨鳥到菜鳥之(六十八)細談Spring(二)自己動手類比spring

來源:互聯網
上載者:User



            在我們學習spring之前,根據spring的特性,我們來自己來類比一個spring出來,也就是說不利用spring來實現spring的效果。本執行個體主要是實現spring的IOC功能。


點擊下載源碼:用力點


首先我們把我們用的dao、service、entity定義出來:

Student.java :

package com.bzu.entity;public class Student {private int id;private String name;private String address;******************set、get方法省略}

因為spring提倡的就是面向介面編程,所以在我們寫dao層和service層具體實現之前,我們先定義介面,讓我們的具體實現實現介面。介面的代碼很簡單,在這就不貼出來了。

StudentdaoImp.javapublic class StudentDaoImp implements StudentDao {public void add(Student stu) {System.out.println("stu is saved");}}

StudentServiceImp.java

public class StudentServiceImp implements StudentService {StudentDao stuDao=null;public StudentDao getStuDao() {return stuDao;}public void setStuDao(StudentDao stuDao) {this.stuDao = stuDao;}@Overridepublic void add(Student stu) {stuDao.add(stu);}}

      這裡要注意的是,我們這裡是類比spring,主要類比spring中的IOC功能,所以在此我們一樣要在service層中定義dao的執行個體,當然不用new出來,我們就通過spring的IOC把這裡的dao層注入進來。不要忘了對dao提供set。Get方法,因為IOC的底層其實就是利用反射機制實現的,他把dao注入進來,其實底層就是通過反射set進來的。

       好了,我們所需的dao層、service層還有entity定義好了之後,萬事俱備只欠東風了,下一步我們就是定義我們自己的ClassPathXmlApplicationContext類了,通過他,在我們new出他的對象的時候,他來載入設定檔,然後把我們的dao操作注入到我們的service層,在spring中,ClassPathXmlApplicationContext類實現了BeanFactory介面,在此我們也定義一個BeanFactory介面,其實這個介面沒什麼具體的作用,我們就是為了來類比spring。在定義這個介面和實作類別之前,我們先來看一下我們所需的xml是怎麼編寫的,下面我們就具體來看一下beans.xml的配置:

Beans.xml:

<beans><bean id="stuDao" class="com.bzu.dao.imp.StudentDaoImp" /><bean id="stuService" class="com.bzu.service.imp.StudentServiceImp" ><property name="stuDao" bean="stuDao"/></bean></beans>

        看到這,相信大家都能感覺到這個設定檔太簡單了,沒有spring中那麼多繁瑣的配置,當然啦,我們這是只是實現其中的一個功能,spring提供了很多那麼強大的功能,配置當然繁瑣一些了。相信上邊的代碼不用我解釋大家也能看懂了吧。

       好了,設定檔我們看完了,下一步我們一起來看一下我們的spring容器——ClassPathXmlApplicationContext具體是怎麼實現的,我們首先還是來看一下他的介面定義:

BeanFactory.java:

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

我們看到,介面其實很簡單,就定義了一個getBean方法,下面我們來看一下具體的實作類別:

ClassPathXmlApplicationContext.java

public class ClassPathXmlApplicationContext implements BeanFactory {private Map<String, Object> beans = new HashMap<String, Object>();public ClassPathXmlApplicationContext() throws Exception, Exception {SAXBuilder sb = new SAXBuilder();Document doc = sb.build(this.getClass().getClassLoader().getResourceAsStream("beans.xml")); // 構造文檔對象Element root = doc.getRootElement(); // 擷取根項目HDList list = root.getChildren("bean");// 取名字為disk的所有元素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();System.out.println(id);System.out.println(clazz);beans.put(id, o);for (Element propertyElement : (List<Element>) element.getChildren("property")) {String name = propertyElement.getAttributeValue("name"); // userDAOString bean = propertyElement.getAttributeValue("bean"); // uObject beanObject = beans.get(bean);// UserDAOImpl instanceString methodName = "set" + name.substring(0, 1).toUpperCase()+ name.substring(1);System.out.println("method name = " + methodName);Method m = o.getClass().getMethod(methodName,beanObject.getClass().getInterfaces()[0]);m.invoke(o, beanObject);}}}@Overridepublic Object getBean(String id) {return beans.get(id);}}

代碼貼出來了,不知道大家看懂沒有。下面我來解釋一下這段代碼: 

      首先我們定義了一個容器Map<String, Object> beans,這個容器的作用就是用來裝我們從設定檔裡解析來的一個個bean,為什麼要用map類型,我想大家也差不多能猜到吧,我們設定檔中每一個bean都有一個id來作為自己的唯一身份。我們把這個id存到map的key裡面,然後value就裝我們的具體bean對象。說完這個容器之後,下面我們在來看一下ClassPathXmlApplicationContext的構造方法,這個構造方法是我們spring管理容器的核心,這個構造方法的前半部分是利用的jdom解析方式,把xml裡面的bean一個個的解析出來,然後把解析出來的bean在放到我們bean容器裡。如果這段代碼看不懂的話,那你只好在去看看jdom解析xml了。好了,我們下面在來看一下這個構造的方法,後半部分主要是在對設定檔進行解析出bean的同時去查看一下這個bean中有沒有需要注射bean的,如果有的話,他就去通過這些裡面的property屬性擷取他要注射的bean名字,然後構造出set方法,然後通過反射,調用注入bean的set方法,這樣我們所需要的bean就被注入進來了。如果這段代碼你看不懂的話,那你只能去看一下有關反射的知識了。最後我們就來看一下實現介面的getBean放了,其實這個方法很簡單,就是根據提供的bean的id,從bean容器內把對應的bean取出來。

好了,我們所需的東西都定義好了,下面我們據來測試一下,看看我們自己模仿的spring到底能不能自動把我們所需要的dao層給我們注入進來。

public static void main(String[] args) throws Exception {ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext();Student stu = new Student();StudentService service = (StudentService) context.getBean("stuService");service.add(stu);}

運行代碼,控制台輸出:

com.bzu.service.imp.StudentServiceImp

method name = setStuDao

stu is saved

       好,成功注入進來,到此,我們模仿的spring就到此結束了,下一篇我們就開始對spring進行一個全面深入瞭解了,敬請期待。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.