spring ioc原理

spring ioc原理java

控制反轉/依賴注入mysql

 

最近,買了本spring入門書:spring In Action 。大體瀏覽了下感受還不錯。就是入門了點。Manning的書仍是不錯的,我雖然不像哪些只看Manning書的人那樣專一於Manning,但懷着崇敬的心情和激情通覽了一遍。又一次接受了IOC 、DI、AOP等Spring核心概念。 先就IOC和DI談一點個人見解。

IOC(DI):其實這個Spring架構核心的概念沒有這麼複雜,更不像有些書上描述的那樣晦澀。Java程序員都知道:java程序中的每一個業務邏輯至少須要兩個或以上的對象來協做完成,一般,每一個對象在使用他的合做對象時,本身均要使用像new object() 這樣的語法來完成合做對象的申請工做。你會發現:對象間的耦合度高了。而IOC的思想是:Spring容器來實現這些相互依賴對象的建立、協調工做。對象只須要關係業務邏輯自己就能夠了。從這方面來講,對象如何獲得他的協做對象的責任被反轉了(IOC、DI)。

這是我對Spring的IOC的體會。DI其實就是IOC的另一種說法。DI是由Martin Fowler 在2004年初的一篇論文中首次提出的。他總結:控制的什麼被反轉了?就是:得到依賴對象的方式反轉了。

若是對這一核心概念還不理解:這裏引用一個叫Bromon的blog上找到的淺顯易懂的答案:



程序員

IoC與DIspring

  首先想說說IoC(Inversion of Control,控制倒轉)。這是spring的核心,貫穿始終。所謂IoC,對於spring框架來講,就是由spring來負責控制對象的生命週期和對象間的關係。這是什麼意思呢,舉個簡單的例子,咱們是如何找女友的?常見的狀況是,咱們處處去看哪裏有長得漂亮身材又好的mm,而後打聽她們的興趣愛好、qq號、電話號、ip號、iq號………,想辦法認識她們,投其所好送其所要,而後嘿嘿……這個過程是複雜深奧的,咱們必須本身設計和麪對每一個環節。傳統的程序開發也是如此,在一個對象中,若是要使用另外的對象,就必須獲得它(本身new一個,或者從JNDI中查詢一個),使用完以後還要將對象銷燬(好比Connection等),對象始終會和其餘的接口或類藕合起來。sql

  那麼IoC是如何作的呢?有點像經過婚介找女友,在我和女友之間引入了一個第三者:婚姻介紹所。婚介管理了不少男男女女的資料,我能夠向婚介提出一個列表,告訴它我想找個什麼樣的女友,好比長得像李嘉欣,身材像林熙雷,唱歌像周杰倫,速度像卡洛斯,技術像齊達內之類的,而後婚介就會按照咱們的要求,提供一個mm,咱們只須要去和她談戀愛、結婚就好了。簡單明瞭,若是婚介給咱們的人選不符合要求,咱們就會拋出異常。整個過程再也不由我本身控制,而是有婚介這樣一個相似容器的機構來控制。Spring所倡導的開發方式就是如此,全部的類都會在spring容器中登記,告訴spring你是個什麼東西,你須要什麼東西,而後spring會在系統運行到適當的時候,把你要的東西主動給你,同時也把你交給其餘須要你的東西。全部的類的建立、銷燬都由 spring來控制,也就是說控制對象生存週期的再也不是引用它的對象,而是spring。對於某個具體的對象而言,之前是它控制其餘對象,如今是全部對象都被spring控制,因此這叫控制反轉。若是你還不明白的話,我決定放棄。數據庫

IoC的一個重點是在系統運行中,動態的向某個對象提供它所須要的其餘對象。這一點是經過DI(Dependency Injection,依賴注入)來實現的。好比對象A須要操做數據庫,之前咱們老是要在A中本身編寫代碼來得到一個Connection對象,有了 spring咱們就只須要告訴spring,A中須要一個Connection,至於這個Connection怎麼構造,什麼時候構造,A不須要知道。在系統運行時,spring會在適當的時候製造一個Connection,而後像打針同樣,注射到A當中,這樣就完成了對各個對象之間關係的控制。A須要依賴 Connection才能正常運行,而這個Connection是由spring注入到A中的,依賴注入的名字就這麼來的。那麼DI是如何實現的呢? Java 1.3以後一個重要特徵是反射(reflection),它容許程序在運行的時候動態的生成對象、執行對象的方法、改變對象的屬性,spring就是經過反射來實現注入的。關於反射的相關資料請查閱java doc。
 理解了IoC和DI的概念後,一切都將變得簡單明瞭,剩下的工做只是在spring的框架中堆積木而已。

若是還不明白,放棄java吧!架構

 

下面來讓你們瞭解一下Spring究竟是怎麼運行的。app

 

Java代碼
  1. public static void main(String[] args) {   
  2.         ApplicationContext context = new FileSystemXmlApplicationContext(   
  3.                 "applicationContext.xml");   
  4.         Animal animal = (Animal) context.getBean("animal");   
  5.         animal.say();   
  6.     }  
 
[java] view plain copy
 
print ?
  1. public static void main(String[] args) {  
  2.         ApplicationContext context = new FileSystemXmlApplicationContext(  
  3.                 "applicationContext.xml");  
  4.         Animal animal = (Animal) context.getBean("animal");  
  5.         animal.say();  
  6.     }  
 
public static void main(String[] args) {
		ApplicationContext context = new FileSystemXmlApplicationContext(
				"applicationContext.xml");
		Animal animal = (Animal) context.getBean("animal");
		animal.say();
	}


這段代碼你必定很熟悉吧,不過仍是讓咱們分析一下它吧,首先是applicationContext.xml框架

Java代碼
  1. <bean id="animal" class="phz.springframework.test.Cat">   
  2.         <property name="name" value="kitty" />   
  3.     </bean>  
 
[java] view plain copy
 
print ?
  1. <bean id="animal" class="phz.springframework.test.Cat">  
  2.         <property name="name" value="kitty" />  
  3.     </bean>  
 
<bean id="animal" class="phz.springframework.test.Cat">
		<property name="name" value="kitty" />
	</bean>


他有一個類phz.springframework.test.Cat網站

Java代碼
  1. public class Cat implements Animal {   
  2.     private String name;   
  3.     public void say() {   
  4.         System.out.println("I am " + name + "!");   
  5.     }   
  6.     public void setName(String name) {   
  7.         this.name = name;   
  8.     }   
  9. }  
 
[java] view plain copy
 
print ?
  1. public class Cat implements Animal {  
  2.     private String name;  
  3.     public void say() {  
  4.         System.out.println("I am " + name + "!");  
  5.     }  
  6.     public void setName(String name) {  
  7.         this.name = name;  
  8.     }  
  9. }  
 
public class Cat implements Animal {
	private String name;
	public void say() {
		System.out.println("I am " + name + "!");
	}
	public void setName(String name) {
		this.name = name;
	}
}


實現了phz.springframework.test.Animal接口

Java代碼
  1. public interface Animal {   
  2.     public void say();   
  3. }  
 
[java] view plain copy
 
print ?
  1. public interface Animal {  
  2.     public void say();  
  3. }  
 
public interface Animal {
	public void say();
}


很明顯上面的代碼輸出I am kitty!

那麼到底Spring是如何作到的呢?
接下來就讓咱們本身寫個Spring 來看看Spring 究竟是怎麼運行的吧!

首先,咱們定義一個Bean類,這個類用來存放一個Bean擁有的屬性

Java代碼
  1. /* Bean Id */  
  2.     private String id;   
  3.     /* Bean Class */  
  4.     private String type;   
  5.     /* Bean Property */  
  6.     private Map<String, Object> properties = new HashMap<String, Object>();  
 
[java] view plain copy
 
print ?
  1. /* Bean Id */  
  2.     private String id;  
  3.     /* Bean Class */  
  4.     private String type;  
  5.     /* Bean Property */  
  6.     private Map<String, Object> properties = new HashMap<String, Object>();  
 
/* Bean Id */
	private String id;
	/* Bean Class */
	private String type;
	/* Bean Property */
	private Map<String, Object> properties = new HashMap<String, Object>();


一個Bean包括id,type,和Properties。

接下來Spring 就開始加載咱們的配置文件了,將咱們配置的信息保存在一個HashMap中,HashMap的key就是Bean 的 Id ,HasMap 的value是這個Bean,只有這樣咱們才能經過context.getBean("animal")這個方法得到Animal這個類。咱們都知道Spirng能夠注入基本類型,並且能夠注入像List,Map這樣的類型,接下來就讓咱們以Map爲例看看Spring是怎麼保存的吧

Map配置能夠像下面的

Java代碼
  1. <bean id="test" class="Test">   
  2.         <property name="testMap">   
  3.             <map>   
  4.                 <entry key="a">   
  5.                     <value>1</value>   
  6.                 </entry>   
  7.                 <entry key="b">   
  8.                     <value>2</value>   
  9.                 </entry>   
  10.             </map>   
  11.         </property>   
  12.     </bean>  
 
[java] view plain copy
 
print ?
  1. <bean id="test" class="Test">  
  2.         <property name="testMap">  
  3.             <map>  
  4.                 <entry key="a">  
  5.                     <value>1</value>  
  6.                 </entry>  
  7.                 <entry key="b">  
  8.                     <value>2</value>  
  9.                 </entry>  
  10.             </map>  
  11.         </property>  
  12.     </bean>  
 
<bean id="test" class="Test">
		<property name="testMap">
			<map>
				<entry key="a">
					<value>1</value>
				</entry>
				<entry key="b">
					<value>2</value>
				</entry>
			</map>
		</property>
	</bean>


Spring是怎樣保存上面的配置呢?,代碼以下:

Java代碼
  1. if (beanProperty.element("map") != null) {   
  2.                     Map<String, Object> propertiesMap = new HashMap<String, Object>();   
  3.                     Element propertiesListMap = (Element) beanProperty   
  4.                             .elements().get(0);   
  5.                     Iterator<?> propertiesIterator = propertiesListMap   
  6.                             .elements().iterator();   
  7.                     while (propertiesIterator.hasNext()) {   
  8.                         Element vet = (Element) propertiesIterator.next();   
  9.                         if (vet.getName().equals("entry")) {   
  10.                             String key = vet.attributeValue("key");   
  11.                             Iterator<?> valuesIterator = vet.elements()   
  12.                                     .iterator();   
  13.                             while (valuesIterator.hasNext()) {   
  14.                                 Element value = (Element) valuesIterator.next();   
  15.                                 if (value.getName().equals("value")) {   
  16.                                     propertiesMap.put(key, value.getText());   
  17.                                 }   
  18.                                 if (value.getName().equals("ref")) {   
  19.                                     propertiesMap.put(key, new String[] { value   
  20.                                             .attributeValue("bean") });   
  21.                                 }   
  22.                             }   
  23.                         }   
  24.                     }   
  25.                     bean.getProperties().put(name, propertiesMap);   
  26.                 }  
 
[java] view plain copy
 
print ?
  1. if (beanProperty.element("map") != null) {  
  2.                     Map<String, Object> propertiesMap = new HashMap<String, Object>();  
  3.                     Element propertiesListMap = (Element) beanProperty  
  4.                             .elements().get(0);  
  5.                     Iterator<?> propertiesIterator = propertiesListMap  
  6.                             .elements().iterator();  
  7.                     while (propertiesIterator.hasNext()) {  
  8.                         Element vet = (Element) propertiesIterator.next();  
  9.                         if (vet.getName().equals("entry")) {  
  10.                             String key = vet.attributeValue("key");  
  11.                             Iterator<?> valuesIterator = vet.elements()  
  12.                                     .iterator();  
  13.                             while (valuesIterator.hasNext()) {  
  14.                                 Element value = (Element) valuesIterator.next();  
  15.                                 if (value.getName().equals("value")) {  
  16.                                     propertiesMap.put(key, value.getText());  
  17.                                 }  
  18.                                 if (value.getName().equals("ref")) {  
  19.                                     propertiesMap.put(key, new String[] { value  
  20.                                             .attributeValue("bean") });  
  21.                                 }  
  22.                             }  
  23.                         }  
  24.                     }  
  25.                     bean.getProperties().put(name, propertiesMap);  
  26.                 }  
 
if (beanProperty.element("map") != null) {
					Map<String, Object> propertiesMap = new HashMap<String, Object>();
					Element propertiesListMap = (Element) beanProperty
							.elements().get(0);
					Iterator<?> propertiesIterator = propertiesListMap
							.elements().iterator();
					while (propertiesIterator.hasNext()) {
						Element vet = (Element) propertiesIterator.next();
						if (vet.getName().equals("entry")) {
							String key = vet.attributeValue("key");
							Iterator<?> valuesIterator = vet.elements()
									.iterator();
							while (valuesIterator.hasNext()) {
								Element value = (Element) valuesIterator.next();
								if (value.getName().equals("value")) {
									propertiesMap.put(key, value.getText());
								}
								if (value.getName().equals("ref")) {
									propertiesMap.put(key, new String[] { value
											.attributeValue("bean") });
								}
							}
						}
					}
					bean.getProperties().put(name, propertiesMap);
				}



接下來就進入最核心部分了,讓咱們看看Spring 究竟是怎麼依賴注入的吧,其實依賴注入的思想也很簡單,它是經過反射機制實現的,在實例化一個類時,它經過反射調用類中set方法將事先保存在HashMap中的類屬性注入到類中。讓咱們看看具體它是怎麼作的吧。
首先實例化一個類,像這樣

Java代碼
  1. public static Object newInstance(String className) {   
  2.         Class<?> cls = null;   
  3.         Object obj = null;   
  4.         try {   
  5.             cls = Class.forName(className);   
  6.             obj = cls.newInstance();   
  7.         } catch (ClassNotFoundException e) {   
  8.             throw new RuntimeException(e);   
  9.         } catch (InstantiationException e) {   
  10.             throw new RuntimeException(e);   
  11.         } catch (IllegalAccessException e) {   
  12.             throw new RuntimeException(e);   
  13.         }   
  14.         return obj;   
  15.     }  
 
[java] view plain copy
 
print ?
  1. public static Object newInstance(String className) {  
  2.         Class<?> cls = null;  
  3.         Object obj = null;  
  4.         try {  
  5.             cls = Class.forName(className);  
  6.             obj = cls.newInstance();  
  7.         } catch (ClassNotFoundException e) {  
  8.             throw new RuntimeException(e);  
  9.         } catch (InstantiationException e) {  
  10.             throw new RuntimeException(e);  
  11.         } catch (IllegalAccessException e) {  
  12.             throw new RuntimeException(e);  
  13.         }  
  14.         return obj;  
  15.     }  
 
public static Object newInstance(String className) {
		Class<?> cls = null;
		Object obj = null;
		try {
			cls = Class.forName(className);
			obj = cls.newInstance();
		} catch (ClassNotFoundException e) {
			throw new RuntimeException(e);
		} catch (InstantiationException e) {
			throw new RuntimeException(e);
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		}
		return obj;
	}


接着它將這個類的依賴注入進去,像這樣

Java代碼
  1. public static void setProperty(Object obj, String name, String value) {   
  2.         Class<? extends Object> clazz = obj.getClass();   
  3.         try {   
  4.             String methodName = returnSetMthodName(name);   
  5.             Method[] ms = clazz.getMethods();   
  6.             for (Method m : ms) {   
  7.                 if (m.getName().equals(methodName)) {   
  8.                     if (m.getParameterTypes().length == 1) {   
  9.                         Class<?> clazzParameterType = m.getParameterTypes()[0];   
  10.                         setFieldValue(clazzParameterType.getName(), value, m,   
  11.                                 obj);   
  12.                         break;   
  13.                     }   
  14.                 }   
  15.             }   
  16.         } catch (SecurityException e) {   
  17.             throw new RuntimeException(e);   
  18.         } catch (IllegalArgumentException e) {   
  19.             throw new RuntimeException(e);   
  20.         } catch (IllegalAccessException e) {   
  21.             throw new RuntimeException(e);   
  22.         } catch (InvocationTargetException e) {   
  23.             throw new RuntimeException(e);   
  24.         }   
  25. }  
 
[java] view plain copy
 
print ?
  1. public static void setProperty(Object obj, String name, String value) {  
  2.         Class<? extends Object> clazz = obj.getClass();  
  3.         try {  
  4.             String methodName = returnSetMthodName(name);  
  5.             Method[] ms = clazz.getMethods();  
  6.             for (Method m : ms) {  
  7.                 if (m.getName().equals(methodName)) {  
  8.                     if (m.getParameterTypes().length == 1) {  
  9.                         Class<?> clazzParameterType = m.getParameterTypes()[0];  
  10.                         setFieldValue(clazzParameterType.getName(), value, m,  
  11.                                 obj);  
  12.                         break;  
  13.                     }  
  14.                 }  
  15.             }  
  16.         } catch (SecurityException e) {  
  17.             throw new RuntimeException(e);  
  18.         } catch (IllegalArgumentException e) {  
  19.             throw new RuntimeException(e);  
  20.         } catch (IllegalAccessException e) {  
  21.             throw new RuntimeException(e);  
  22.         } catch (InvocationTargetException e) {  
  23.             throw new RuntimeException(e);  
  24.         }  
  25. }  
 
public static void setProperty(Object obj, String name, String value) {
		Class<? extends Object> clazz = obj.getClass();
		try {
			String methodName = returnSetMthodName(name);
			Method[] ms = clazz.getMethods();
			for (Method m : ms) {
				if (m.getName().equals(methodName)) {
					if (m.getParameterTypes().length == 1) {
						Class<?> clazzParameterType = m.getParameterTypes()[0];
						setFieldValue(clazzParameterType.getName(), value, m,
								obj);
						break;
					}
				}
			}
		} catch (SecurityException e) {
			throw new RuntimeException(e);
		} catch (IllegalArgumentException e) {
			throw new RuntimeException(e);
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		} catch (InvocationTargetException e) {
			throw new RuntimeException(e);
		}
}


最後它將這個類的實例返回給咱們,咱們就能夠用了。咱們仍是以Map爲例看看它是怎麼作的,我寫的代碼裏面是建立一個HashMap並把該HashMap注入到須要注入的類中,像這樣,

Java代碼
  1. if (value instanceof Map) {   
  2.                 Iterator<?> entryIterator = ((Map<?, ?>) value).entrySet()   
  3.                         .iterator();   
  4.                 Map<String, Object> map = new HashMap<String, Object>();   
  5.                 while (entryIterator.hasNext()) {   
  6.                     Entry<?, ?> entryMap = (Entry<?, ?>) entryIterator.next();   
  7.                     if (entryMap.getValue() instanceof String[]) {   
  8.                         map.put((String) entryMap.getKey(),   
  9.                                 getBean(((String[]) entryMap.getValue())[0]));   
  10.                     }   
  11.                 }   
  12.                 BeanProcesser.setProperty(obj, property, map);   
  13.             }  
 
[java] view plain copy
 
print ?
  1. if (value instanceof Map) {  
  2.                 Iterator<?> entryIterator = ((Map<?, ?>) value).entrySet()  
  3.                         .iterator();  
  4.                 Map<String, Object> map = new HashMap<String, Object>();  
  5.                 while (entryIterator.hasNext()) {  
  6.                     Entry<?, ?> entryMap = (Entry<?, ?>) entryIterator.next();  
  7.                     if (entryMap.getValue() instanceof String[]) {  
  8.                         map.put((String) entryMap.getKey(),  
  9.                                 getBean(((String[]) entryMap.getValue())[0]));  
  10.                     }  
  11.                 }  
  12.                 BeanProcesser.setProperty(obj, property, map);  
  13.             }  
 
if (value instanceof Map) {
				Iterator<?> entryIterator = ((Map<?, ?>) value).entrySet()
						.iterator();
				Map<String, Object> map = new HashMap<String, Object>();
				while (entryIterator.hasNext()) {
					Entry<?, ?> entryMap = (Entry<?, ?>) entryIterator.next();
					if (entryMap.getValue() instanceof String[]) {
						map.put((String) entryMap.getKey(),
								getBean(((String[]) entryMap.getValue())[0]));
					}
				}
				BeanProcesser.setProperty(obj, property, map);
			}

好了,這樣咱們就能夠用Spring 給咱們建立的類了,是否是也不是很難啊?固然Spring能作到的遠不止這些,這個示例程序僅僅提供了Spring最核心的依賴注入功能中的一部分。 本文參考了大量文章沒法一一感謝,在這一塊兒感謝,若是侵犯了你的版權深表歉意,很但願對你們有幫助!

相關文章
相關標籤/搜索