`
Luob.
  • 浏览: 1574624 次
  • 来自: 上海
社区版块
存档分类
最新评论

Spring 简单应用

阅读更多
下面使用的 spring-3.0版本来演示

目标任务
1.配置最简单的,spring 应用 
2.使用spring管理ServiceBean
3.手动编写代码 模拟 spring的初始工作



1.首先来看 spring 应用中最基本的jar




2.spring的配置文件 (可以从spring的文档中拷贝,或者 spring自带的 案例中拷贝)
<?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/context 
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/beans   
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd "> 

</beans> 


3.就这样 我们就可以 来初始化 spring 容器  编写单元测试
package junit.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringTest {

	@Test //测试 spring的 初始化
	public void init(){
		ApplicationContext context=new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
		
	}
}


//上面 如果测试单元没有问题 就说明 spring 框架 使用成功 !! 恭喜 !!

4.下面 来看 使用 spring容器来管理我们的 bean (首先定义bean--->然后配置)
package com.person.service;

public interface PersonService {
	public void save();
}


package com.person.service.impl;

import com.person.service.PersonService;

public class PersonServiceBean implements PersonService {
	public void save(){
		System.out.println("我就是save方法!");
	}
}


5.在spring配置文件中配置
<?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/context 
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/beans   
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd "> 

	<!-- 这里配置后 就会有 spring来管理, 注意id 和name 的区别  -->
	<bean id="personService" class="com.person.service.impl.PersonServiceBean">
	</bean>
</beans>   
 


6.测试
package junit.test;

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

import com.person.service.PersonService;

public class SpringTest {

	@Test //测试 spring的 初始化
	public void init(){
		ApplicationContext ctx=new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
		
		
		//方法一  获取服务层对象
		PersonService personService=(PersonService)ctx.getBean("personService");
		//方法二
		PersonService personService1=ctx.getBean("personService",PersonService.class);
		
		personService.save();
		personService1.save();
		
	}
}


//如果能在控制台 打印出  "我就是save方法!" 恭喜成功!

7.看了上面这么多  那么spring到底怎么初始化 和 管理的 我们的bean呢? 我们自己来模拟写一个 spring的 init 初始工作 (使用 dom4j 来读取配置文件 -->使用 反射来创建对象)



8.首先加入  dom4j-1.6.1.jar 和  jaxen.jar(dom4j需要的一个jar)

9.定义隐射spring配置文件bean 的类

package junit.test;

/**
 * 定义  保存 spring配置文件中的bean对象
 * @author Bin
 */
public class BeanDefinition {
	
	private String id;  //对应 spring配置文件中的id
	private String className;   //对应 spring配置文件中的class 
	//get set
       // 构造方法 
}


10.定义 我们自己的 读取spring配置文件中的 ClassPathXmlApplicationContext 类
package junit.test;


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;

import com.sun.xml.internal.fastinfoset.stax.events.Util;


/*
 * 来模拟spring 的工作
 */
public class MySpringClassPathXmlApplicationContext {
	
	//保存 配置文件中的 bean 的信息  
	private List<BeanDefinition> beandefines=new ArrayList<BeanDefinition>();
	
	
	//保存初始化 后的对象
	private Map<String,Object> sigletons=new HashMap<String,Object>();
	
	
	public MySpringClassPathXmlApplicationContext(String fileName) {
		this.readXml(fileName);
		this.instanceBean();
	}

	/**==================
	 *   读取xml配置文件
	 * ==================
	 * @author Bin
	 * @param fileName
	 */
	private void readXml(String fileName) {
		SAXReader saxReader=new SAXReader();
		Document doucment=null;
		try {
			URL xmlPath=this.getClass().getClassLoader().getResource(fileName);
			doucment=saxReader.read(xmlPath);
			Map<String,String> nsMap=new HashMap<String,String>();
			//给spring配置文件的命名空间  一个别名 ns
			nsMap.put("ns","http://www.springframework.org/schema/beans"); //加入命名空间  xmlns: spring配置文件中的
			XPath xsub=doucment.createXPath("//ns:beans/ns:bean"); //创建 beans/bean 查询路径
			
			xsub.setNamespaceURIs(nsMap); //设置命名空间
			List<Element> beans=xsub.selectNodes(doucment); //获取文档下的所有bean节点
			
			for (Element element : beans) {
				String id=element.attributeValue("id"); //获取 id的属性值
				String clazz=element.attributeValue("class"); // 获取 class属性

				//类是 spring中的 : org.springframework.beans.factory.config.BeanDefinition;
				BeanDefinition beandefine=new BeanDefinition(id,clazz);
				beandefines.add(beandefine);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**===================================
	 *   完成Bean 的实例化
	 * ===================================
	 * @author Bin
	 */
	private void instanceBean() {
		for (BeanDefinition beandefine : beandefines) {
			try {
				if(!Util.isEmptyString(beandefine.getClassName()))
					sigletons.put(beandefine.getId(), Class.forName(beandefine.getClassName().trim()).newInstance());
			}catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	/**=======================
	 *    获取bean 
	 * =====================
	 * @param beanName
	 * @return
	 */
	public Object getBean(String beanName){
		return this.sigletons.get(beanName);
	}
	
}


11.好啦 我们来测试吧

	@Test  //测试 自定义的spring 模拟器
	public void testMySpring(){
		MySpringClassPathXmlApplicationContext ctx=new MySpringClassPathXmlApplicationContext("applicationContext.xml");
		//方法一  获取服务层对象
		PersonService personService=(PersonService)ctx.getBean("personService");
		personService.save();
	}



//如果  同样看到  "我就是save方法!"  我想 你应该对spring有所了解了吧??  嘻嘻
//睡觉啦 呵呵  88
  • 大小: 44.3 KB
1
2
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics