20160503-spring入门2

使用Spring需要的jar
到http://www.springsource.org/download下载spring,然后进行解压缩,在解压目录中找到下面jar文件,拷贝到类路径下
 
dist\spring.jar
lib\jakarta-commons\commons-logging.jar
如果使用了切面编程(AOP),还需要下列jar文件
lib/aspectj/aspectjweaver.jar和aspectjrt.jar
lib/cglib/cglib-nodep-2.1_3.jar
如果使用了JSR-250中的注解,如@Resource/@PostConstruct/@PreDestroy,还需要下列jar文件
lib\j2ee\common-annotations.jar
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/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
          <bean id="personService" class="cn.itcast.service.impl.PersonServiceBean"></bean>
</beans>
实例化spring容器
实例化Spring容器常用的两种方式:
 
方法一:
在类路径下寻找配置文件来实例化容器
ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{"beans.xml"});
 
方法二:
在文件系统路径下寻找配置文件来实例化容器
ApplicationContext ctx = new FileSystemXmlApplicationContext(new String[]{“d:\\beans.xml“});
 
Spring的配置文件可以指定多个,可以通过String数组传入。
 
从spring容器中得到bean
当spring容器启动后,因为spring容器可以管理bean对象的创建,销毁等生命周期,所以我们只需从容器直接获取Bean对象就行,而不用编写一句代码来创建bean对象。从容器获取bean对象的代码如下:
 
 
ApplicationContext ctx = new ClassPathXmlApplicationContext(“beans.xml”);
OrderService service = (OrderService)ctx.getBean("personService");

实例代码:

1.编写配置文件:

 

<?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="personService" class="com.dzq.service.impl.PersonServiceBean"></bean>
</beans>

 

 

 

2.编写接口及其实现:

接口:

package com.dzq.service;

public interface PersonService {

    public abstract void save();

}

实现:

 

package junit.test;

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

import com.dzq.service.PersonService;

public class SpringTest {

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
    }

    @Test
    public void instanceSpring() {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
        PersonService service= (PersonService) ctx.getBean("personService");//从配置文件获取bean
        service.save();
        
    }

}

 

 spring读取配置文件的原理:

 

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;
    }
    
}

 

 

 

使用dom4j读取spring配置文件
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);
    }
}

 

三种实例化bean的方式
 
1.使用类构造器实例化
 
<bean id=“orderService" class="cn.itcast.OrderServiceBean"/>

 

2.使用静态工厂方法实例化
<bean id="personService" class="cn.itcast.service.OrderFactory" factory-method="createOrder"/>

 

public class OrderFactory {
    public static OrderServiceBean createOrder(){
        return new OrderServiceBean();
    }
}

 

3.使用实例工厂方法实例化:
<bean id="personServiceFactory" class="cn.itcast.service.OrderFactory"/>
<bean id="personService" factory-bean="personServiceFactory" factory-method="createOrder"/>

 

public class OrderFactory {
public OrderServiceBean createOrder(){
return new OrderServiceBean();
}
}

 

 
Bean的作用域
.singleton
 在每个Spring IoC容器中一个bean定义只有一个对象实例。默认情况下会在容器启动时初始化bean,但我们可以指定Bean节点的lazy-init=“true”来延迟初始化bean,这时候,只有第一次获取bean会才初始化bean。如:
<bean id="xxx" class="cn.itcast.OrderServiceBean" lazy-init="true"/>
如果想对所有bean都应用延迟初始化,可以在根节点beans设置default-lazy-init=“true“,如下
<beans default-lazy-init="true“ ...>
.prototype
 每次从容器获取bean都是新的对象。
 
.request
.session
.global session
 
 
指定Bean的初始化方法和销毁方法
<bean id="xxx" class="cn.itcast.OrderServiceBean" init-method="init" destroy-method="close"/>

 

 

 

 

 
 
posted @ 2016-05-04 21:09  破玉  阅读(245)  评论(0编辑  收藏  举报