IOC原理
將對象創建交給Spring去管理。
實現IOC的兩種方式
-
IOC配置文件的方式
-
IOC注解的方式
IOC底層實現原理
- 底層實現使用的技術
1.1 xml配置文件
1.2 dom4j解析xml
1.3 工廠模式
1.4 反射
Spring的IOC實現過程
- 導入Jar包
* 如果做Spring最基本的功能,只需要導入最基本的四個即可。(Beans、Core、Context、SpEL)。
* 因為Spring沒有提供日志功能,所以除了上述jar包之外,還要有輸出日志的jar包(commons-logging.jar和log4j.jar)。
- 創建類,在類中創建方法:創建一個簡單的類。
- 創建Spring配置文件,配置創建類
* Spring核心配置文件名稱和位置不是固定的。 一般為Maven項目中resources下的ApplicationContext.xml。
* 引入約束。
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
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
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<beans>
* 配置Bean
<bean id="user" class="com.yl.user">
</bean>
-
寫代碼測試創建過程:
//獲取xml對象 ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml"); //通過xml對象獲取bean User user = (User) context.getBean("user"); System.out.println(user.toString());