<beans xmlns="https://www.springframework.org/schema/beans" ...> <bean id="address" class="com.cn.test.spring.Address"/> </beans>
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-application.xml");
Address address = (Address) ctx.getBean("address");
從 classpath 讀取配置,適用獨立 Java 程序。
從文件系統絕對路徑加載,較少用。
// Servlet 中獲取
WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext());
Address address = (Address) wac.getBean("address");
<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>
默認加載 /WEB-INF/applicationContext.xml,可用 <context-param> 指定自定義路徑。
ClassPathXmlApplicationContextApplicationContext 即 IOC 容器,管理 Bean 生命周期與依賴注入