在J2EE环境中,Spring 有一种典型的用法:为J2EE web应用提供逻辑中间层的基本骨架。Spring提供"web应用上下文"的概念,将一个强大的轻量级IoC容器无缝结合到web环境中。
示例:
在一个典型的Spring web应用中,applicationContext.xml文件存放于WEB_INFO目录中,其中包含了bean的声明。这个文件中定义了业务对象和资源对象。Spring将负责管理所有这些bean的配置、关联和生命周期。
<beans>
<bean id="myDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<property name="url">
<value>jdbc:mysql:myds</value>
</property>
</bean>
<bean id="myInventoryManager" class="ebusiness.DefaultInventoryManager">
<property name="dataSource">
<ref bean="myDataSource" />
</property>
</bean>
<bean id="myProductManager" class="ebusiness.DefaultInventoryManager">
<property name="inventoryManager">
<ref bean="myInventoryManager" />
</property>
<property name="retrieveCurrentStock">
<value>true</value>
</property>
</bean>
</beans>
在默认情况下,所有的Bean都是通过Singleton模式创建的。
我们在web.xml中定义一个监听器,用于加载根应用上下文。
<web-app>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
</web-app>
初始化完成后,整个web应用都可以从ServletContext的一个属性中取得根应用上下文,就象取得其他对象一样。另外也可以通过org.springframework.web.context.support.WebApplicationContextUtils 的方法快速获得所需的应用上下文。
WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(servletContext);
浙公网安备 33010602011771号