在Spring中有兩個很是重要的概念,控制反轉和依賴注入;控制反轉將依賴對象的建立和管理交由Spring容器,而依賴注入則是在控制反轉的基礎上將Spring容器管理的依賴對象注入到應用之中;java
所謂依賴注入:在運行期,由外部容器動態將依賴對象注入到組件中。spring
XML文件解析 + Java反射技術;apache
首先是XML文件的解析(dom4j),Spring框架對於配置文件的選擇是XML文件,根據Spring的規範,配置文件的命名是沒有特殊要求的,只是在文件的放置位置上有兩種選擇;類路徑下或者操做系統文件目錄下(大多數狀況是放到類路徑下)。json
對於Spring的控制反轉和依賴注入來講,惟一使用的是配置文件中的<bean>標籤,經過這個標籤,Spring就完成了對象的建立和依賴對象的注入工做;數組
一、首先對於配置文件中的<bean>節點,在Spring框架中存在一個對用的定義接口,叫作BeanDefinition;子啊個類定義了得到<bean>節點中出現的全部屬性的方法,例如classNam、scope、factory-method、lazy-init 等等屬性;app
二、對於<bean>節點的子節點property則完成了屬性注入的功能;屬性注入有三種方式,構造器注入、屬性setter方法注入和註解方式注入;框架
三、若是是setter方法注入,對於類屬性XML配置文件中有兩種方法,一是使用property節點的ref屬性,一是使用property幾點的子節點bean進行內部bean配置;若是是對於基本數據類型進行配置,那麼要是用property節點的value屬性;dom
定義本身的關於bean節點、property節點的pojo類文件;this
使用注入DOM4J等開源包講配置文件解析讀入;spa
使用Java的反射技術講配置文件中的信息setter到咱們須要的屬性中去;common-beanutils.jar
- <context:component-scan base-package="com.sample"/>
- <bean id="personService" class="com.spring.junit.test.impl.PersonServiceImpl"></bean>
- <bean id="stockService" class="com.spring.junit.test.impl.StockServiceImpl"></bean>
-
- <bean id="personServiceFactory" class="com.spring.junit.test.impl.PersonServiceBeanFactory" factory-method="createPersonServiceBeanFactory"></bean>
-
- <bean id="personServiceFactory2" class="com.spring.junit.test.impl.PersonServiceBeanFactory"></bean>
- <bean id="stockServiceFactory" factory-bean="personServiceFactory2" factory-method="createStockServiceBeanFactory"></bean>
-
- <bean id="randomBean" class="com.spring.junit.bean.StaticFactoryBean" factory-method="createRandom" scope="prototype"></bean>
-
-
-
- 經過setter方法注入
- <bean id="user" class="com.sample.bean.User"></bean>
- <bean id="personDao" class="com.sample.dao.impl.PersonDaoBeanImpl"></bean>
- <bean id="personService" class="com.sample.service.impl.PersonServiceBeanImpl">
-
- <property name="personDao" ref="personDao"></property>
- <property name="name" value="jackjson_xu_test"></property>
- <property name="id" value="108"></property>
- <property name="sets">
- <set>
- <value>第一個</value>
- <value>第二個</value>
- <value>第三個</value>
- </set>
- </property>
- <property name="lists">
- <list>
- <value>第一個list元素</value>
- <value>第二個list元素</value>
- <value>第三個list元素</value>
-
- </list>
- </property>
- <property name="properties">
- <props>
- <prop key="key1">value1</prop>
- <prop key="key2">value2</prop>
- <prop key="key3">value3</prop>
-
- </props>
- </property>
- <property name="maps">
- <map>
- <entry key="key-1" value="value-1"></entry>
- <entry key="key-2" value="value-2"></entry>
- <entry key="key-3" value="value-3"></entry>
- <entry key="key-4" value="value-4"></entry>
- </map>
- </property>
- <property name="users">
- <map>
- <entry key="U_1001">
- <ref bean="user"/>
- </entry>
- <entry key="U_1002">
- <ref bean="user"/>
- </entry>
- </map>
- </property>
- </bean>
-
-
- <bean id="personService" class="com.sample.service.impl.PersonServiceBeanImpl">
- <property name="personDao">
- <bean class="com.sample.dao.impl.PersonDaoBeanImpl"/>
- </property>
- <property name="name" value="jackjson_xu_test"></property>
- <property name="id" value="100"></property>
- </bean>
-
-
-
-
- <bean id="personDao" class="com.sample.dao.impl.PersonDaoBeanImpl"></bean>
- <bean id="personService2" class="com.sample.service.impl.PersonServiceBeanImpl2" autowire="byType">
- <constructor-arg index="0" type="com.sample.dao.IPersonDao" ref="personDao"></constructor-arg>
- <constructor-arg index="1" type="java.lang.String" value="http://www.woyo.com"></constructor-arg>
- </bean>
-
package com.sample.junit;
- import java.util.ArrayList;
- import java.util.List;
-
-
-
-
-
- public class BeanDefinition {
- private String id;
- private String className;
- private List<PropertyDefinition> propertys = new ArrayList<PropertyDefinition>();
-
- 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;
- }
-
- public List<PropertyDefinition> getPropertys() {
- return propertys;
- }
-
- public void setPropertys(List<PropertyDefinition> propertys) {
- this.propertys = propertys;
- }
- }
package com.sample.junit;
-
-
-
-
-
-
- public class PropertyDefinition {
- private String name;
- private String ref;
- private String value;
-
- public PropertyDefinition(String name, String ref, String value) {
- this.name = name;
- this.ref = ref;
- this.value = value;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getRef() {
- return ref;
- }
-
- public void setRef(String ref) {
- this.ref = ref;
- }
-
- public String getValue() {
- return value;
- }
-
- public void setValue(String value) {
- this.value = value;
- }
-
- }
package com.sample.junit;
- import java.beans.Introspector;
- import java.beans.PropertyDescriptor;
- import java.lang.reflect.Field;
- import java.lang.reflect.Method;
- import java.net.URL;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
-
- import org.apache.commons.beanutils.ConvertUtils;
- import org.apache.log4j.Logger;
- import org.dom4j.Document;
- import org.dom4j.Element;
- import org.dom4j.XPath;
- import org.dom4j.io.SAXReader;
-
-
-
-
-
- public class SampleClassPathXMLApplicationContext {
- private Logger logger = Logger.getLogger(SampleClassPathXMLApplicationContext.class);
- private List<BeanDefinition> beanDefines = new ArrayList<BeanDefinition>();
- private Map<String, Object> sigletons = new HashMap<String, Object>();
-
- public SampleClassPathXMLApplicationContext(String filename) {
- this.readXML(filename);
- this.instanceBeans();
- this.annotationInject();
- this.injectObject();
- }
-
-
-
-
-
- private void annotationInject() {
- for (String beanName : sigletons.keySet()) {
- Object bean = sigletons.get(beanName);
- if (bean != null) {
- this.propertyAnnotation(bean);
- this.fieldAnnotation(bean);
- }
- }
- }
-
-
-
-
- private void propertyAnnotation(Object bean) {
- try {
-
- PropertyDescriptor[] ps = Introspector.getBeanInfo(bean.getClass()).getPropertyDescriptors();
- for (PropertyDescriptor properdesc : ps) {
-
- Method setter = properdesc.getWriteMethod();
-
- if (setter != null && setter.isAnnotationPresent(SampleResource.class)) {
-
- SampleResource resouce = setter.getAnnotation(SampleResource.class);
- Object value = null;
- if (resouce.name() != null && !"".equals(resouce.name())) {
- value = sigletons.get(resouce.name());
- setter.setAccessible(true);
- setter.invoke(bean, value);
- } else {
- value = sigletons.get(resouce.name());
- if (value == null) {
- for (String key : sigletons.keySet()) {
-
- if (properdesc.getPropertyType().isAssignableFrom(sigletons.get(key).getClass())) {
- value = sigletons.get(key);
- }
- }
- }
-
- setter.setAccessible(true);
-
- setter.invoke(bean, value);
- }
- }
- }
- } catch (Exception e) {
- logger.error(e.getLocalizedMessage());
- }
- }
-
-
-
-
- private void fieldAnnotation (Object bean) {
- try {
-
- Field[] fields = bean.getClass().getFields();
- for (Field field : fields) {
- if (field.isAnnotationPresent(SampleResource.class)) {
- SampleResource resouce = field.getAnnotation(SampleResource.class);
- Object value = null;
- if (resouce.name() != null && !"".equals(resouce.name())) {
- value = sigletons.get(resouce.name());
- } else {
- value = sigletons.get(field.getName());
- if (value == null) {
- for (String key : sigletons.keySet()) {
-
- if (field.getType().isAssignableFrom(sigletons.get(key).getClass())) {
- value = sigletons.get(key);
- break;
- }
- }
- }
- }
- field.setAccessible(true);
- field.set(bean, value);
- }
- }
- } catch (Exception e) {
- e.getLocalizedMessage();
- logger.error("字段註解解析異常:" + e.getLocalizedMessage());
- }
- }
-
-
-
- private void injectObject() {
- for (BeanDefinition beanDefinition : beanDefines) {
- Object bean = sigletons.get(beanDefinition.getId());
- if (bean != null) {
- try {
- PropertyDescriptor[] ps = Introspector.getBeanInfo(bean.getClass()).getPropertyDescriptors();
- for (PropertyDefinition propertyDefinition : beanDefinition.getPropertys()) {
- for (PropertyDescriptor properdesc : ps) {
- if (propertyDefinition.getName().equals(properdesc.getName())) {
- Method setter = properdesc.getWriteMethod();
- if (setter != null) {
- Object value = null;
- if (propertyDefinition.getRef() != null && !"".equals(propertyDefinition.getRef().trim())) {
- value = sigletons.get(propertyDefinition.getRef());
- } else {
- value = ConvertUtils.convert(propertyDefinition.getValue(), properdesc.getPropertyType());
- }
- setter.setAccessible(true);
- setter.invoke(bean, value);
- }
- break;
- }
- }
- }
- } catch (Exception e) {
- }
- }
- }
- }
-
-
-
-
- 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();
- }
- }
- }
-
-
-
-
-
-
- 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);
- for (Element element : beans) {
- String id = element.attributeValue("id");
- String clazz = element.attributeValue("class");
- BeanDefinition beanDefine = new BeanDefinition(id, clazz);
- XPath propertysub = element.createXPath("ns:property");
- propertysub.setNamespaceURIs(nsMap);
- List<Element> propertys = propertysub.selectNodes(element);
- for (Element property : propertys) {
- String propertyName = property.attributeValue("name");
- String propertyref = property.attributeValue("ref");
- String propertyValue = property.attributeValue("value");
- PropertyDefinition propertyDefinition = new PropertyDefinition(propertyName, propertyref, propertyValue);
- beanDefine.getPropertys().add(propertyDefinition);
- System.out.println("propertyName:" + propertyName + "|propertyref:" + propertyref + "|propertyValue:" + propertyValue);
- }
- beanDefines.add(beanDefine);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
-
-
-
-
-
-
- public Object getBean(String beanName) {
- return this.sigletons.get(beanName);
- }
- }
package com.sample.junit;
- import org.junit.BeforeClass;
- import org.junit.Test;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
-
- import com.sample.service.IPersonService;
-
- public class SpringTest {
-
- static ApplicationContext ctx = null;
- @BeforeClass
- public static void setUpBeforeClass() throws Exception {
- ctx = new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml"});
- }
-
-
- @Test public void instanceSpring(){
- IPersonService personService = (IPersonService)ctx.getBean("personService");
- System.out.println(personService);
- personService.save();
- }
-
-
- }