Spring兩大核心概念之IOC

IOC(Invension of Control 控制反轉),原來屬性由自己控制,自己創建對象進行初始化;現在由Spring容器控制,反轉到容器了。解耦同時更靈活,對象可以隨意裝配。
DI(Dependency Injection 依賴注入),比如UserDao的屬性是依賴Spring容器注入進來的,不是自己在類中寫死的。Spring內部原理就是依靠反射實現的。
即從實現具體的初始化到抽象層次初始化。
以下是一個基於XML的配置元數據的基本結構:

<?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-2.5.xsd">

  <bean id="..." class="...">
    <!-- collaborators and configuration for this bean go here -->
  </bean>

  <bean id="..." class="...">
    <!-- collaborators and configuration for this bean go here -->
  </bean>

  <!-- more bean definitions go here -->

</beans>

1.建立Spring的User Library,加入spring.jar和commons-logging.jar。對UserService進行JUnit測試(在類同級的地方new一個JUnit Test Case,拖到test的source folder裏,run as Junit test即可)。

2.查api(在jar包上-properties-javadoc location中加入api路徑),點擊類後按F1即可在右邊javadoc窗口查看到。
查看構造方法後得知可以加多個xml文件方便開發。

BeanFactory factory = new ClassPathXmlApplicationContext("beans.xml");

或者

ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");

BeanFactory 還是 ApplicationContext?

BeanFactory接口擅長於處理bean的初始化和配置,而 ApplicationContext接口除了處理上述工作外,它還針對企業引用 提供了許多基礎支持,比如事務處理和AOP。

簡而言之,一般把ApplicationContext接 口作爲首選。

總之,模擬spring的bean工廠就是模擬BeanFactory和ClassPathXmlApplicationContext這兩個類。
具體用時模擬效果和spring中使用的是一樣的。
都是先聲明上下文

ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");

再從容器中拿實例化的bean即可

UserService service = (UserService) factory.getBean("userService");
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章