Spring學習筆記(三)

本教程對應視頻課程:http://edu.51cto.com/course/14731.html

1、ioc和di

1.1、IOC容器

1.1.1、ObjectFactory 和ApplicationContext

BeanFactory:這個接口是spring中最底層的接口,只提供了最簡單的IoC功能(創建bean,獲取bean,銷燬bean)

在一般的應用當中,一般不使用BeanFactory;推薦用ApplicationContext(應用上下文);

1.ApplicationContext繼承了BeanFactory,提供了基本的IoC功能;

2.ApplicationContext還提供了其他功能,比如支持國際化,消息機制,統一的資源加載,AOP功能等

1.1.2、ApplicationContext的實現類

1、ClassPathXmlApplicationContext:讀取classpath中的資源

ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

2、FileSystemXmlApplicationContext

ApplicationContext ac = new FileSystemXmlApplicationContext("c:/licationContext.xml");

3、XmlWebApplicationContext

XmlWebApplicationContext ac = new XmlWebApplicationContext();
// 需要指定ServletContext對象
ac.setServletContext(servletContext);
// 指定配置文件路徑,開頭的斜線表示Web應用的根目錄
ac.setConfigLocation("/WEB-INF/applicationContext.xml"); 
// 初始化容器
ac.refresh(); 

1.1.2、Resource常用實現類

ClassPathResource:從classpath根路徑開始找配置文件

FileSystemResource:從磁盤的文件路徑去找c://xx.xml

ServletContextResource:應用於web中,從web中去找配置文件

1.2、Bean的創建時機

1.ApplicationContext在加載的時候就會創建所有的bean(Web應用建議)

2.BeanFactory需要等到拿bean的時候纔會創建bean(延遲加載)(桌面程序)

延遲加載

ApplicationContext做到延遲加載的效果:
針對於當前xml中所有的bean。

<beans default-lazy-init="default | false | true">

針對於指定的bean:

<beans lazy-init="default | false | true">

1.3、Bean的作用域

<bean id="" class="" scope="作用域"/>

singleton: 單例 :在Spring IoC容器中僅存在一個Bean實例 (默認的scope)

prototype: 多例 :每次從容器中調用Bean時,都返回一個新的實例,即每次調用getBean()時 ,相當於執行new 不會在容器啓動時創建對象

對於MVC中的Action(Struts2)使用prototype類型,其他使用singleton

1.4、初始化和銷燬方法

<bean id="someBean" class="......" 
        init-method="該類中初始化方法名" destroy-method="該類中銷燬方法名">
</bean>

init-method:bean生命週期初始化方法,對象創建後就進行調用

destroy-method:容器被銷燬的時候,如果bean被容器管理,會調用該方法。

如果bean的scope="prototype",那麼容器只負責創建和初始化,它並不會被spring容器管理。

1.5、Bean的實例化的方式

1.5.1、構造器

構造器實例化,最標準,使用最多

java類

public class SomeBean1 {}

xml配置

<bean id="someBean1" class="SomeBean1全限定名"/>

1.5.2、靜態工廠方式

java類

public class SomeBean2Factory {
    public static SomeBean2 getSomeBean2(){
        return new SomeBean2();
    }
}
public class SomeBean2 {}

xml配置

<bean id="someBean2" class="SomeBean2Factory全限定名" factory-method="getSomeBean2"/>

此時我們通過上下文對象獲取id爲someBean2的對象,這個對象的類型爲SomeBean2

1.5.3、實例工廠方式

實例工廠方法實例化:解決系統遺留問題,有點麻煩,使用比較少

public class SomeBean3 {}
public class SomeBean3Factory {
    public SomeBean3 getSomeBean3() {
        return new SomeBean3();
    }
}

xml配置

<bean id="someBean3Factory" class="SomeBean3Factory全限定名"/>
<bean id="someBean3" factory-bean="someBean3Factory" factory-method="getSomeBean3"/>

此時我們獲取id爲someBean3的對象,實際上會創建實例工廠,然後在通過實例工廠的工廠方法來或者SomeBean3的對象

1.5.4、實現FactoryBean接口實例化

java類

public class SomeBean4 {}
public class SomeBean4FactoryBean implements FactoryBean<SomeBean4>{
     //返回對象
    public SomeBean4 getObject() throws Exception {
        return new SomeBean4();
    }
     //返回對象的類型
    public Class<?> getObjectType() {
        return SomeBean4.class;
    }
     //返回是否單例
    public boolean isSingleton() {
        return true;
    }
}

xml配置

<bean id="someBean4" class="SomeBean4FactoryBean全限定名" />

1.6、DI和ioc介紹

IoC(inverse of control):指將對象的創建權,反轉到Spring容器;

DI (Dependency Injection) :指Spring創建對象的過程中,將對象依賴屬性通過配置進行注入 。

其實它們是同一個概念的不同角度描述。DI相對IoC而言,明確描述了”被注入對象依賴IoC容器配置依賴對象”。

1.6.1、注入方式

使用setter注入:

1.使用bean元素的property子元素設置;

​ 簡單類型值,直接使用value賦值;

​ 引用類型,使用ref賦值;

​ 集合類型,直接使用對應的集合類型元素即可。

2.spring通過屬性的setter方法注入值;

3.在配置文件中配置的值都是string,spring可以自動的完成類型的轉換

4.屬性的設置值是在init方法執行之前完成的

構造器注入

1.spring在實例化對象的時候,如果對象沒有配置constructor-arg,則使用默認的構造器實例化對象

2.如果有constructor-arg,那麼spring使用這些constructor-arg來唯一確定一個構造器

1.6.2、注入值的類型

1、簡單類型數據

java類編寫

public class Employee {
    private String name;
    private Integer age;
    private Double salary;
    private URL url;
       省略setter/getter
}

xml配置

<bean id="employee" class="cn.org.kingdom.vo.Employee">
        <property name="name" value="kingdom" />
        <property name="age" value="17" />
        <property name="salary" value="123" />
        <property name="url" value="http://urlValue" />
</bean>

2.對象類型的值

java類

public class EmpDAO {
    public void save(){
        System.out.println("EmpDAO.save()");
    }
}
public class EmpService {
    private EmpDAO dao;//持有一個引用數據類型

    public void setDao(EmpDAO dao) {
        this.dao = dao;
    }

    public void save() {
        dao.save();
        System.out.println("EmpService.save()");
    }
}

xml文件配置

<bean id="empDAO" class="cn.org.kingdom.vo.EmpDAO" />
<bean id="empService" class="cn.org.kingdom.vo.EmpService">
        <property name="dao" ref="empDAO" />
</bean>

3.注入集合類型

java類

public class ConnectionBean {
    private Set<String> set;
    private List<String> list;
    private String[] array;
    private Map<String, String> map;
    private Properties prop;
       省略setter/getter
}

xml文件配置

<bean id="collectionBean" class="cn.org.kingdom.dbc.ConnectionBean">
        <property name="set">
            <set>
                <value>set1</value>
                <value>set2</value>
                <value>set3</value>
            </set>
        </property>
        <property name="list">
            <list>
                <value>list1</value>
                <value>list2</value>
                <value>list3</value>
            </list>
        </property>
        <property name="array">
            <list>
                <value>array1</value>
                <value>array2</value>
                <value>array3</value>
            </list>
        </property>
        <property name="map">
            <map>
                <entry key="key1" value="value1"/>
                <entry key="key2" value="value2"/>
                <entry key="key3" value="value3"/>
            </map>
        </property>
        <property name="prop">
            <props>
                <prop key="pKey1">pVal1</prop>
                <prop key="pKey2">pVal2</prop>
                <prop key="pKey3">pVal3</prop>
            </props>
        </property>
    </bean>

1.7、屬性佔位符

1、添加jar包

使用DataSource的案例,給數據源注入Property中的數據加入相關jar包支持

commons-dbcp-1.2.2.jar、commons-pool-1.5.3.jar、com.springsource.oracle.jdbc-10.2.0.2.jar

2、引入context命名空間

<?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:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        ">
</beans>

3、拷貝db.properties文件

db.driver=oracle.jdbc.driver.OracleDriver
db.url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
db.username=scott
db.password=tiger

4、加載配置文件

<context:property-placeholder location="classpath:db.properties"/>
<bean id = "ds" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="${db.driver}"></property>
        <property name="url" value="${db.url}"></property>
        <property name="username" value="${db.username}"></property>
        <property name="password" value="${db.password}"></property>
</bean>

5、測試

package cn.org.kingdom.test;
import org.apache.commons.dbcp.BasicDataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4Cla***unner;
@RunWith(SpringJUnit4Cla***unner.class)
@ContextConfiguration
public class SpringTest {
    @Autowired
    private BeanFactory factory;
    @Autowired
    private AbstractApplicationContext ctx ; 
    @Test
    public void testSpringTest() throws Exception {
        BasicDataSource ds = (BasicDataSource) ctx.getBean("ds");
        System.out.println(ds.getConnection());
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章