2、用eclipse创建一个新的web项目,如创建web项目名为spring3,并做如下操作:
(1)在WebContent下建立一个index.jsp,接着将该项目部署到tomcat上测试web环境是否搭建成功;
(2)将下载的spring包解压,拷贝里面的lib文件下的所有jar包到项目的/spring3/WebContent/WEB-INF/lib下;
(3)spring3需要用到log包,去下载commons-logging-1.0.4.jar,并放到项目lib下;
3、配置sping3配置文件
(1)在项目下新建一个源文件夹config,并在该文件夹下新建一个applicationContext.xml的配置文件,文件内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
">
<bean id="user" class="com.demo.User"></bean>
</beans>
4、创建一个测试类User
(1)新建一个User类,代码如下:
package com.demo;
public class User {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
5、以application启动spring并测试
(1)创建一个UserApp来测试启动并使用spring,代码如下:
package com.demo;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class UserApp {
/**
* @param args
*/
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{"classpath:applicationContext.xml"});
User u = (User) ctx.getBean("user");
u.setName("张三");
System.out.println("你好,"+u.getName()+"!");
}
}
运行成功后控制台会输出:你好,张三!
6、以web方式启动spring3
(1)打开web.xml,在web-app中间加入如下代码:
<!-- 配置路径参数 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext.xml
</param-value>
</context-param>
<!-- 启动spring -->
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>