Spirng管理bean示例

来源:互联网 发布:java ssh框架项目源码 编辑:程序博客网 时间:2024/05/17 23:40

1:新建一个JAVA工程 SpringDemo
2:为SpringDemo工程导入Spring2.5核心jar,并在在src目录下建立spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans
 xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:p="http://www.springframework.org/schema/p"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">


</beans>
3:建立单元测试类 Junit 4 Test 测试Spring环境的搭建是否成功
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class SpringTest {
 @Test
 public void getInstanceSpring(){
  ApplicationContext ctx=new ClassPathXmlApplicationContext("spring.xml");
 }
}
4:新建一个普通业务Bean
package com.xinyang.services.impl;

import com.xinyang.services.PersionService;


public class PersionServiceBean implements PersionService {
 /* (non-Javadoc)
  * @see com.xinyang.services.impl.PersionService#set()
  */
 public void set()
 {
   System.out.println("Sprng第一个应用");
 }
}
对已有的方法抽取接口:OersuibService(通过Eclipse先导实现) 业务类-->Refactor-->Extract Interface(抽取接口)
当然接口和实现类最好不要同一目录下 通过 名称-->Refactor-->Move 到具体的某个包中
5 :更改配置文件 把业务Bean交给Spring管理
<bean id="persionService" class="com.xinyang.services.impl.PersionServiceBean"></bean>
6:更改单元测试类,在Spring容器中获取业务Bean并通过其接口对其引用

public class SpringTest {
 @Test
 public void getInstanceSpring(){
  ApplicationContext ctx=new ClassPathXmlApplicationContext("spring.xml");
  PersionService  persionService=(PersionService)ctx.getBean("persionService");
  persionService.set();
 }
}
以上实现如何把bean交给Spirng容器进行管理,并从Spring容器中获取Bean实例

7:创建一个类,模拟Spring容器利用dom4j读取Spring配置文件
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;

/***
 *
 * @author Administrator
 *
 */

public class ClassPathXMLApplicationContext {
 private List<BeanDefinition> beanDefines =new ArrayList<BeanDefinition> ();
 
 
 //通过名称取得实例
 private Map<String,Object> sigletons=new HashMap<String, Object>();
 /***
  * 模拟spring内部实现 首先要读取spring配置文件
  * 一:读取xml配置文件readXML();
  * 二:通过反射机制 实例化bean对象
  *
  */
 public ClassPathXMLApplicationContext(String filename){
  //读取配置文件
  this.readXML(filename);
  this.instanceBeans();
 }
 /**
  * 完成bean的实例化
  */
private void instanceBeans() {
  // TODO Auto-generated method stub
 //因为首先执行this.readXML(filename)这个方法 ,所以它会把xml配置信息读取并出入至beanDefines集合里
  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) {
    // TODO Auto-generated catch blocksssss
    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");//加入命名空间
   //要读取的内容是bean元素里面的内容 它会从根节点开始找 首先是beans->bean
   //beans 节点所在的命名空间 在ns(http://www.springframework.org/schema/beans)中,所以需加上命名空间前缀  通过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);
    beanDefines.add(beanDefine);
   }
   
  }catch(Exception e){
   e.printStackTrace();
  }
 }
 /**
  * 获取bean实例
  * @param beanName
  * @return  Object
  */
 public Object getBean(String beanName){
  return this.sigletons.get(beanName);
 }
 
}
8:创建一个javaBean  BeanDefinition用于存放读取bean的信息
package junit.test;

public class BeanDefinition {
 private String id;
 private String className;
 public BeanDefinition(String id, String className) {
  super();
  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;
 }
 
}

9:更改测试测试类
ClassPathXMLApplicationContext ctx=new ClassPathXMLApplicationContext("applicationContext.xml");
   SpringService services=(SpringService)ctx.getBean("persionService");
  services.set();


package junit.test;


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

import com.xinyang.services.SpringService;
public class SpringTest {

 @BeforeClass
 public static void setUpBeforeClass() throws Exception {
 }
 @Test
 public void instanceSpring(){
  
  ClassPathXMLApplicationContext ctx=new ClassPathXMLApplicationContext("applicationContext.xml");
   SpringService services=(SpringService)ctx.getBean("persionService");
  services.set();
   
 }

}

这样测试的结果
java.lang.NoClassDefFoundError: org/jaxen/JaxenException
  XPath xsub=document.createXPath("//ns:beans/ns:bean");显示这段代码有问题
这时需导入:jaxen-1[1].1-beta-6.jar

原创粉丝点击