您的位置:首页 > 编程语言 > Java开发

java三大框架spring之spring自动配置web环境

2016-08-19 20:12 597 查看
 在 WEB 环境下使用 Spring

①. 需要额外加入的 jar 包:

spring-web-4.0.0.RELEASE.jar

spring-webmvc-4.0.0.RELEASE.jar

②. Spring 的配置文件, 和非 WEB 环境没有什么不同

③. 需要在 web.xml 文件中加入如下配置:

<!-- 配置 Spring 配置文件的名称和位置 -->

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>

</context-param>

<!-- 启动 IOC 容器的 ServletContextListener -->

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

</listener>

在其需要用到IOC容器的地方直接调用即可。代码如下:

<%@page import="com.levi.spring.struts2.beans.Person"%>
<%@page import="org.springframework.web.context.support.WebApplicationContextUtils"%>
<%@page import="org.springframework.context.ApplicationContext"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

<%
//1. 从 appication 域对象中得到 IOC 容器的实例
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(application);

//2. 从 IOC 容器中得到 bean
Person person = ctx.getBean(Person.class);

//3. 使用 bean
person.hello();
%>

</body>
</html>其中还需要配置下bean那些
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java spring配置web