雖然Spring已經火了這麼多年了,工作中也有偶爾接觸到,卻沒有怎麼深入瞭解。現在作爲一個小白開始學習,也是以此博客作爲一個記錄,如果有不對的地方,希望大家指出來,共同探討。
今天跟大家一起學習下有關spring中ApplicationContext的相關內容。
bean是spring中的管理的對象,所有的組件在spring中都會當成一個bean來處理。bean在spring容器中運行,spring容器負責創建bean。
一、ApplicationContext可以用來創建bean
ApplicationContext的三個常用實現類:
- ClassPathXmlApplicationContext:它可以加載類路徑下的配置文件,要求配置文件必須在類路徑下。不在的話,加載不了。
- FileSystemXmlApplicationContext:它可以加載磁盤任意路徑下的配置文件(必須有訪問權限)
- AnnotationConfigApplicationContext:它是用於讀取註解創建容器的。
example:
場景:賬戶操作
定義了一個業務層操作接口:AccountService
public interface AccountService {
void saveAccount();
}
業務層接口的實現類:AccountServiceImpl
public class AccountServiceImpl implements AccountService {
@Override
public void saveAccount() {
}
}
定義了持久層操作接口:AccountDao
public interface AccountDao {
void saveAccount();
}
定義了持久層操作實現類:AccountDaoImpl
public class AccountDaoImpl implements AccountDao {
@Override
public void saveAccount() {
System.out.println("保存賬戶成功");
}
}
(1)我們通過ClassPathXmlApplicationContext來創建bean
public class TestClient {
/**
* 獲取spring的IOC容器,並根據id獲取對象
*
* @param args
*/
public static void main(String[] args) {
// 1、獲取核心容器
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
AccountService accountService = (AccountService) context.getBean("accountService");
AccountDao accountDao = context.getBean("accountDao", AccountDao.class);
System.out.println(accountService);
System.out.println(accountDao);
}
}
我們可以看到這兩個bean已經創建成功了。
(2)我們通過FileSystemXmlApplicationContext來創建bean,這個時候,我們需要指定配置文件的絕對路徑
public class TestClient {
/**
* 獲取spring的IOC容器,並根據id獲取對象
*
* @param args
*/
public static void main(String[] args) {
// 1、獲取核心容器
ApplicationContext context = new FileSystemXmlApplicationContext("//Users/apple/Documents/git-source/my-source/spring_test_02/src/main/resources/bean.xml");
AccountService accountService = (AccountService) context.getBean("accountService");
AccountDao accountDao = context.getBean("accountDao", AccountDao.class);
System.out.println(accountService);
System.out.println(accountDao);
}
}
/Users/apple/Documents/git-source/my-source/spring_test_02/src/main/resources/bean.xml是我本地文件的絕對路徑
運行結果:
他也拿到了兩個bean。
關於第三種AnnotationConfigApplicationContext用註解的方式創建bean,我們下一次在演示。
二、ApplicationContext與BeanFactory的區別
- ApplicationContext:
- 在構建核心容器時,創建對象採取的策略是立即加載的方式。也就是說一讀取完配置文件,馬上就創建配置文件中配置的對象。
- BeanFactory:
- 在構建核心容器時,創建對象採取的策略是延遲加載的方式,也就說,什麼時候根據id獲取對象了,什麼時候真正創建對象。