Spring IOC與Bean容器

布still發表於2017-09-19

什麼是IOC

IOC:控制反轉,控制權的轉移,應用程式本身不負責依賴物件的建立和維護,而是由外部容器負責建立和維護
DI(依賴注入):一種實現方式
目的:建立物件並且組裝物件之間的關係

Bean容器初始化

基礎包:

  • org.springframework.beans
  • org.springframework.context
  • BeanFactory提供配置結構和基本功能,載入並初始化Bean
  • ApplicationContext儲存了Bean物件並在Spring中被廣泛使用

ApplicationContext方式

  • 本地檔案

    //絕對路徑
    FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext("F:/workspace/appcontext.xml");
  • Classpath

    //相對路徑
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring-context.xml");
  • Web應用中依賴servlet或Listener

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>context</servlet-name>
        <servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    

相關文章