1.IoC(Inversion of Control)控制反轉
A:控制:控制的雙方是什麼?誰控制誰?
主控方:Spring
被控方:應用程序所使用的資源
(原始)應用程序控制自己執行操作需要使用的外部資源
(Spring)Spring控制整個程序中所需要使用的外部資源
B.反轉:什麼是反轉?反轉什麼?
正向:應用程序直接調用資源
反向:應用程序依賴Spring爲其提供資源
反轉的是資源的控制權
應用程序由主動調用資源,變爲被動的等待Spring提供資源
C.有什麼好處?
正向缺點:應用程序控制的資源分佈在程序的每一個地方
反向的優點:所有的資源都在Spring中,便於管理
總結:Spring反向控制應用程序所需要使用的外部資源。資源受Spring管理,利用率最大化。
2.Spring模型演化過程
A.基於分層設計
UserAction 使用UserService,new UserService()
UserService 使用UserDAO,new UserDAO()
UserDAO
B.工廠模式,使用面向接口編程設計,解決層與層之間的緊耦合
製作接口,製作實現類,製作對象工廠
C.工廠模式+配置
製作XML文件,將實現類配置到XML文件中
讀取XML文件中的配置信息,得到實現類的類名
使用反射思想,獲取實現類對象 class.newInstance();
D.Spring設計雛形 自動的工廠+配置
工廠由Spring提供,實現類使用XML格式配置
3.IoC基礎實例
A.導入jar包(6個)
B.製作log4j對應的配置文件
C.在src目錄下創建核心配置文件applicationContext.xml
說明:格式可以從xsd-config.html獲取
<?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.xsd
">
</beans>
D.將應用程序需要使用的資源配置成Spring的Bean
<!-- Spring管理的資源全部聲明到配置文件中 -->
<!-- 所有資源以Bean的形式存在 --> <!-- bean:聲明一個資源Bean --> <!-- bean:id:用於區分bean的標識 --> <!-- bean:class:bean對應的模型類名 --> <bean id="userDao" class="cn.itcast.spring.ioc.UserDao"> </bean> E.創建ApplicationContext對象 ApplicationContext ctx = new ClassPathXmlApplicationContext("配置文件名"); ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); F.獲取Bean對象 使用應用上下文對象獲取 ctx.getBean("bean的id屬性值"); ctx.getBean("userService"); 補充:使用文件系統獲取配置信息,要求配置文件在工程路徑下(少用) ApplicationContext ctx = new FileSystemXmlApplicationContext("applicationContext.xml");