1、Spring在web应用中的使用
- (1)导入额外的jar包:
spring-web-4.0.0.RELEASE.jar
spring-webmvc-4.0.0.RELEASE.jar
- (2)创建IOC容器的步骤
a) 非 web 应用在 main 方法中直接创建
b) 在 web 应用被服务器加载的时候就创建IOC容器
- 在ServletContextListener的
#contextInitialized(ServletContextEvent sce)
方法中创建 IOC 容器, 然后放入 application 域的一个属性中 - Spring 配置文件的名字和位置应该也是可配置的! 将其配置到当前 WEB 应用的初始化参数中较为合适.Spring提供了上述的监听器
- 在ServletContextListener的
2、Spring整合Struts2
- (1) 导入额外的jar包, 正常加入struts2的环境
- (2) 在web.xml中配置
<!-- 配置Spring的用于初始化容器对象的监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext*.xml</param-value>
</context-param>
- (3)在struts.xml配置action的时候, 将class属性设置为action在Spring配置文件中的id, 并且为action加上scope属性prototype. 要是以注解的形式则同理比如
@Controller
@Scope("prototype")
(4) 加入 struts2-spring-plugin-2.3.15.3.jar, Struts2 会先从 IOC 容器中
获取 Action 的实例.
if (appContext.containsBean(beanName)) {
o = appContext.getBean(beanName);
} else {
Class beanClazz = getClassInstance(beanName);
o = buildBean(beanClazz, extraContext);
}