Spring框架---温习(转)

Spring是什么?
   Spring是一个开源的控制反转(Inversion of Control,IoC)和面向切面(AOP)的容器框架,它的主要目的是简化企业开发。
IOC 控制反转
   先看一下一段代码

public class PersonServiceBean{
   private PersonDao personDao = new PersonDaoBean();
   public void save(Person person){
      personDao.save(person);
   }
}

PersonDaoBean是在应用内部(PersonServiceBean)创建及维护的。所以控制反转就是应用本身不负责依赖对象的创建及维护。依赖对象的创建及维护是由外部容器负责的。这样控制权就由应用转移到了外部容器,控制权的转移就是所谓反转。
依赖注入(Dependency Injection)
当我们把依赖对象交给外部容器负责创建,那么PersonServiceBean类可以改成如下:

public class PersonServiceBean{
     private PersonDao personDao;
   //通过构造器参数,让容器把创建好的依赖对象注入进PersonServiceBean,当然也可以使用setter方法进行注入。
     public PersonServiceBean(PersonDao personDao){
         this.personDao = personDao ;
  }
    public void save(Person person){
        personDao.save(person);
  }
}

所谓依赖注入就是指:在运行期,由外部容器动态地将依赖对象注入到组件中。
为什么要使用Spring?
   1.降低组件之间的耦合度,实现软件各层之间的解耦。
                Controller ——》Service ——》 DAO
   2.可以使用容器提供的众多服务,如事务管理服务、消息服务等。当我们使用容器管理事务时,开发人员就不再需要手工控制事务,也不需处理复杂的事物传播。
       
 


   3.容器提供单例模式支持。开发人员不再需要自己填写实现代码。
   4.容器提供了AOP技术,利用它很容易实现如权限拦截、运行期监控等功能。
   5.容器提供的众多辅助类,使用这些类能够加快应用的开发,如JDBC Template、Hibernate Template。
   6.Spring对于主流的应用框架提供了集成支持,如集成Hibernate、JPA、Struts等,这样更便于应用的开发。

搭建与测试Spring的开发环境
 使用版本为Spring2.5.6

新建一个Java Project 命名为spring 并导入相关的jar包
配置Spring配置文件

在src下新建beans.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
</beans>


实例化Spring容器 建议用方法一

新建一个单元测试SpringTest,并导入测试所用的包

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(){
        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
            }
}


新建一个业务Bean,命名为PersonServiceBean;抽取PersonServiceBean的接口。

package cn.itcast.service.impl;

import cn.itcast.service.PersonService;
public class PersonServiceBean implements PersonService {

    public void save(){
        System.out.println("我是save()方法");
    }
}

package cn.itcast.service;

public interface PersonService {

    public void save();

}

在配置文件中加入如下语句实现
<bean id="personService" class="cn.itcast.service.impl.PersonServiceBean"></bean>
注意:编写spring配置文件时,不能出现帮助信息 同通过如下方法解决


修改SpringTest代码 

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(){
        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
        PersonService personService = (PersonService)ctx.getBean("personService");
        personService.save();
    }
}

在实例化了容器之后,从容器中取得bean,再调用业务bean的save方法

执行SpringTest文件 观察控制台输出



以上证明本Spring程序运行成功!

编码剖析Spring管理Bean的原理

通过第一个实例我们会有一个疑问,Spring到底是怎么管理Bean的呢?
我们来模拟Spring的内部实现
在junit.test下新建ItcastClassPathXMLApplicationContext类

类的完全代码(这里要引入dom4j的jar包)

package junit.test;

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
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> sigletons = new HashMap<String, Object>();
   
    public ItcastClassPathXMLApplicationContext(String filename){
        this.readXML(filename);
        this.instanceBeans();
    }
    /**
     * 完成bean的实例化
     */
    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();
            }
        }
       
    }
    /**
     * 读取xml配置文件
    * @param filename
     */
    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);//获取文档下所有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
     */
    public Object getBean(String beanName){
        return this.sigletons.get(beanName);
    }
}


新建BeanDefinition ,用来存放bean里面的两个属性 id 和 className。

package junit.test;

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


修改SpringTest代码 测试程序

package junit.test;
import org.junit.BeforeClass;
import org.junit.Test;
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();
    }
}


执行测试 控制台输出为


说明我们新建的传智播客容器取到了bean实例 并成功地调用了save方法
通过实例,我们就可以理解Spring是创建和管理bean的!

posted on 2009-05-08 13:22 彭伟 阅读(272) 评论(0)  编辑  收藏 所属分类: 框架技术分区


只有注册用户登录后才能发表评论。


网站导航:
 
<2009年5月>
262728293012
3456789
10111213141516
17181920212223
24252627282930
31123456

导航

统计

常用链接

留言簿(3)

随笔分类

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜