首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Spring 實戰入門(一):IOC 容器啟動與 Bean 獲取

     編輯:Java 綜合教學

一、Spring 配置文件

<beans xmlns="https://www.springframework.org/schema/beans" ...>
  <bean id="address" class="com.cn.test.spring.Address"/>
</beans>

二、三種 ApplicationContext 實現

1. ClassPathXmlApplicationContext(Java SE 環境)

ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-application.xml");
Address address = (Address) ctx.getBean("address");

從 classpath 讀取配置,適用獨立 Java 程序。

2. FileSystemXmlApplicationContext

從文件系統絕對路徑加載,較少用。

3. XmlWebApplicationContext(Web 環境)

// Servlet 中獲取
WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext());
Address address = (Address) wac.getBean("address");

三、Web 環境啟動 IOC 容器兩種方式

1. ContextLoaderListener(主流,Servlet 2.4+)

<listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

2. ContextLoaderServlet(兼容 Servlet 2.3)

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

默認加載 /WEB-INF/applicationContext.xml,可用 <context-param> 指定自定義路徑。

四、總結

  • Java SE:手動創建 ClassPathXmlApplicationContext
  • Web 容器:配置 Listener/Servlet 由服務器啟動時自動創建
  • 核心:ApplicationContext 即 IOC 容器,管理 Bean 生命周期與依賴注入
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved