Spring基於xml解決程式間的耦合
阿新 • • 發佈:2022-03-29
引言
Spring的Ioc容器,用於解決程式之間的耦合,通過配置檔案和反射獲取物件。(工廠模式思想)
框架自帶工廠模式
配置檔案
<?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 https://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="accountService" class="com.czy.service.impl.AccountServiceImpl"></bean> <bean id="accountDao" class="com.czy.dao.impl.AccountDaoImpl"></bean> </beans>
通過配置檔案與對映獲取物件(單例物件)
package com.czy.ui; import com.czy.service.AccountService; import com.czy.service.impl.AccountServiceImpl; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * 模擬儲存賬戶 */ public class Client { /** * 獲取spring的Ioc核心容器,並根據id獲取物件 * @param args */ public static void main(String[] args){ //1.獲取核心容器物件 ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml"); //2.根據id獲取bean物件 AccountService service0 = ac.getBean("accountService",AccountService.class); AccountService service = (AccountService)ac.getBean("accountService"); System.out.println(service0); System.out.println(service); } }
Application三個常用實現類(BeanFactory)
1.ClassPathXmlApplicationContext
它可以載入類路徑下的配置檔案,要求配置檔案必須在類路徑下。不在的話,載入不了(maven工程裡的resources)
//1.獲取核心容器物件 ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml"); //2.根據id獲取bean物件 AccountService service0 = ac.getBean("accountService",AccountService.class); AccountService service = (AccountService)ac.getBean("accountService");
2.FileSystemXmlApplicationContext
它可以載入磁碟任意路徑下的配置檔案(必須有訪問許可權)
//1.獲取核心容器物件
ApplicationContext ac = new FileSystemXmlApplicationContext("E:\\JAVA\\Spring\\day01_eesy_02Spring\\src\\main\\resources\\bean.xml");
//2.根據id獲取bean物件
AccountService service0 = ac.getBean("accountService",AccountService.class);
AccountService service = (AccountService)ac.getBean("accountService");
3.AnnotationConfigApplicationContext
它用於讀取註解建立容器的。