spring2 IOC selfImplement record

package cn.itcast.dao;

public interface PersonDao {

	public abstract void add();

}

package cn.itcast.dao.impl;

import cn.itcast.dao.PersonDao;

public class PersonDaoBean implements PersonDao {
	/* (non-Javadoc)
	 * @see cn.itcast.dao.impl.PersonDao#add()
	 */
	public void add(){
		System.out.println("execute add() in PersonDaoBean");
	}
}

package cn.itcast.service;

public interface PersonService {

	public abstract void save();

}

package cn.itcast.service.impl;

import cn.itcast.dao.PersonDao;
import cn.itcast.service.PersonService;

public class PersonServiceBean implements PersonService {
	/* (non-Javadoc)
	 * @see cn.itcast.service.impl.PersonService#save()
	 */
	private PersonDao personDao;
	public PersonDao getPersonDao() {
		return personDao;
	}
	public void setPersonDao(PersonDao personDao) {
		this.personDao = personDao;
	}
	public void save(){
		personDao.add();
		System.out.println("Iam save()");
	}
}

package cn.itcast.service.impl;

public class PersonServiceBeanFactory {
	public static PersonServiceBean createPersonServiceBean(){
		return new PersonServiceBean();
	}
	
	public PersonServiceBean createPersonServiceBean2(){
		return new PersonServiceBean();
	}
}

package junit.test;

import java.util.ArrayList;
import java.util.List;

public class BeanDefinition {
	private String id;
	private String className;
	private List<PropertyDefinition> properties = 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> getProperties() {
		return properties;
	}
	public void setProperties(List<PropertyDefinition> properties) {
		this.properties = properties;
	}
}

package junit.test;

import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
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.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.XPath;
import org.dom4j.io.SAXReader;

public class ItcastClassPathXMLApplicationContext {
	private List<BeanDefinition> beanDefines = new ArrayList<BeanDefinition>();
	private Map<String,Object> singletons = new HashMap<String , Object>();
	public ItcastClassPathXMLApplicationContext(String filename){
		this.readXML(filename);
		this.instanceBeans();
		this.injectObject();
	}
	/**
	 * 爲bean對象的屬性注入值
	 */
	private void injectObject() {
		// TODO Auto-generated method stub
		for(BeanDefinition beanDefinition:beanDefines){
			Object bean = singletons.get(beanDefinition.getId());
			if(bean != null){
				try {
					PropertyDescriptor[] ps = Introspector.getBeanInfo(bean.getClass()).getPropertyDescriptors();
					for(PropertyDefinition propertyDefinition:beanDefinition.getProperties()){
						for(PropertyDescriptor properdesc:ps){
							if(propertyDefinition.getName().equals(properdesc.getName())){
								Method setter = properdesc.getWriteMethod();//get property setter method
								if(setter!=null){
									Object value = singletons.get(propertyDefinition.getRef());
									setter.setAccessible(true);//
									setter.invoke(bean, value);//把引用對象注入到屬性
								}
							}
						}
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		}
	}
	/**
	 * 完成bean實例化
	 */
	private void instanceBeans() {
		for(BeanDefinition beanDefinition:beanDefines){
			try {
				if(beanDefinition.getClassName()!=null&&!"".equals(beanDefinition.getClassName().trim()))
					singletons.put(beanDefinition.getId(), Class.forName(beanDefinition.getClassName()).newInstance());
			} catch (InstantiationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	
	}
/**
 * 讀取xml配置文件
 * @param filename
 */
	private void readXML(String filename) {
		// TODO Auto-generated method stub
		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);
				XPath propertysub = element.createXPath("ns:property");
				propertysub.setNamespaceURIs(nsMap);
				List<Element> properties = propertysub.selectNodes(element);
				for(Element property:properties){
					String propertyName = property.attributeValue("name");
					String propertyref = property.attributeValue("ref");
					System.out.println(propertyName+"="+propertyref);
					PropertyDefinition propertyDefinition = new PropertyDefinition(propertyName,propertyref);
					beanDefine.getProperties().add(propertyDefinition);
				}
				beanDefines.add(beanDefine);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public Object getBean(String beanName){
		return this.singletons.get(beanName);
	}
}

package junit.test;

import java.util.ArrayList;
import java.util.List;

public class PropertyDefinition {
	private String name;
	private String ref;
	
	public PropertyDefinition(String name, String ref) {
		this.name = name;
		this.ref = ref;
	}
	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;
	}

}

package junit.test;


import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.itcast.service.PersonService;

public class SpringTest {

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
	}
	
	@Test
	public void instanceSpring(){
		ItcastClassPathXMLApplicationContext ctx = new ItcastClassPathXMLApplicationContext("beans.xml");
		PersonService personService = (PersonService)ctx.getBean("personService");
		personService.save();
		
//		PersonService personService6 = (PersonService) ctx.getBean("personService");
		
		ApplicationContext ctx2 = new ClassPathXmlApplicationContext("beans.xml");
		PersonService personService2 = (PersonService)ctx2.getBean("personService2");
		personService2.save();
		
		ApplicationContext ctx3 = new ClassPathXmlApplicationContext("beans.xml");
		PersonService personService3 = (PersonService)ctx3.getBean("personService3");
		personService3.save();
		
		PersonService personService4 = (PersonService)ctx.getBean("personService");
		System.out.println(personService==personService4);
		
		PersonService personService5 = (PersonService)ctx2.getBean("personService2");
		System.out.println(personService2==personService5);
	}

}

<?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-2.5.xsd">
			<bean id="personDao" class="cn.itcast.dao.impl.PersonDaoBean"></bean>
			<bean id="personService" class="cn.itcast.service.impl.PersonServiceBean" >
				<property name="personDao" ref="personDao"></property>
			</bean>
			<!-- scope="prototype" 表示了生成的類不是使用單例模式,默認的爲單例模式進行生成 -->
			<bean id="personService2" class="cn.itcast.service.impl.PersonServiceBeanFactory" factory-method="createPersonServiceBean" scope="prototype">
				<property name="personDao" ref="personDao"></property>
			</bean>
			<bean id="personServiceFactory" class="cn.itcast.service.impl.PersonServiceBeanFactory" />
			<bean id="personService3" factory-bean="personServiceFactory" factory-method="createPersonServiceBean2">
				<property name="personDao" ref="personDao"></property>
			</bean>
			 
</beans>


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