一、Spring的開發步驟:
spring各個版本中:
在3.0以下的版本,源碼有spring中相關的所有包【spring功能 + 依賴包】,如2.5版本。
在3.0以上的版本,源碼中只有spring的核心功能包【沒有依賴包】(如果要用依賴包,需要單獨下載!)
1、源碼,jar文件(spring-framework-3.2.5.RELEASE):
commons-logging-1.1.3.jar 日誌
spring-beans-3.2.5.RELEASE.jar bean節點
spring-context-3.2.5.RELEASE.jar spring上下文節點
spring-core-3.2.5.RELEASE.jar spring核心功能
spring-expression-3.2.5.RELEASE.jar spring表達式相關表
以上是必須引入的5個jar文件,在項目中可以用戶庫管理!
2、核心配置文件: applicationContext.xml
1)Spring配置文件:applicationContext.xml / bean.xml
2)配置文件的約束條件參考:
spring-framework-3.2.5.RELEASE\docs\spring-framework-reference\htmlsingle\index.html
<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"
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、API
public class App {
// 1. 通過工廠類得到IOC容器創建的對象
@Test
public void testIOC() throws Exception {
// 之前創建對象使用
// User user = new User();
// 現在,把對象的創建交給spring的IOC容器
Resource resource = new ClassPathResource("mfq/test/applicationContext.xml");
// 創建容器對象(Bean的工廠), IOC容器 = 工廠類 + applicationContext.xml
BeanFactory factory = new XmlBeanFactory(resource);
// 得到容器創建的對象
User user = (User) factory.getBean("user");
// 測試
System.out.println(user.getId());
}
//2. (方便)直接得到IOC容器對象
@Test
public void testAc() throws Exception {
// 得到IOC容器對象
ApplicationContext ac = new ClassPathXmlApplicationContext("mfq/test/applicationContext.xml");
// 從容器中獲取bean
User user = (User) ac.getBean("user");
// 測試
System.out.println(user);
}
}
二、bean對象創建的細節
/**
* 1) 對象創建: 單例/多例
* scope="singleton", 默認值, 即默認是單例 【service/dao/工具類】
* scope="prototype", 多例; 【Action對象】
*
* 2) 什麼時候創建?
* scope="prototype" 在用到對象的時候,才創建對象。
* scope="singleton" 在啓動(容器初始化之前),就已經創建了bean,且整個應用只有一個。
* 3) 是否延遲創建
* lazy-init="false" 默認爲false, 不延遲創建,即在啓動時候就創建對象
* lazy-init="true" 延遲初始化, 在用到對象的時候才創建對象
* (只對單例有效)
* 4) 創建對象之後,初始化/銷燬
* init-method="init_user" 【對應對象的init_user方法,在對象創建愛之後執行 】
* destroy-method="destroy_user" 【在調用容器對象的destriy方法時候執行,(容器用實現類)】
*/
@Test
public void testIOC() throws Exception {
// 得到IOC容器對象 【用實現類(ClassPathXmlApplicationContext),因爲要調用銷燬的方法,而不是接口(ApplicationContext)】
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("mfq/test/applicationContext.xml");
//測試
System.out.println("-----容器創建-----");
// 從容器中獲取bean
User user1 = (User) ac.getBean("user");
User user2 = (User) ac.getBean("user");
//測試
System.out.println(user1);
System.out.println(user2);
// 銷燬容器對象
ac.destroy();
}