一、导包
1.Spring开发包的下载
说明:spring-framework-4.2.4.RELEASE-dist 文件为spring的开发包文件,该文件夹下包含有三个文件夹
其中doc文件夹为说明文档,lib文件夹下包含了Spring开发需要的jar包,schema文件夹下包含了Spring开发需要的约束。
spring-framework-3.0.2.RELEASE-dependencies文件夹为Spring支持的常见的依赖包。
2、在web项目中导入Spring开发包
第一步:在spring-framework-4.2.4.RELEASE-dist /lib选择要导入的开发包。
图上为Spring的模块图。
首先要导入的包为Core container(核心)包:Beans, core ,context ,Spel 粘贴到web项目的lib文件夹下
其次导入Spring依赖包中的common loging包,该包为日志包,旧版本的还需要导入log4j日志包,同样也需要在依赖包中寻找。
导入后的lib文件夹如下:
二、创建对象
1.src文件夹下新建包package com.linfeng.springlearning,再在包下新建类User,如下:
package com.linfeng.springlearning;
public class User {
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
2、书写配置文件,把对象配置到容器。
新建xml文件,配置文件的位置、命名是任意的,但是建议放到src下写成applicationContext.xml
3、导入约束
比较麻烦,参照视频,略过
4、书写applicationContext.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd ">
<!-- 将USER配置到容器 -->
<bean name="user" class="com.linfeng.springlearning.User"></bean>
</beans>
三、代码测试
1、新建测试类
新建包com.linfeng.pringlearning_test,之后新建类test,代码如下:
package com.linfeng.pringlearning_test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.linfeng.springlearning.User;
public class test {
@Test
public void fun1() {
//1创建容器对象
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContest.xml");
//2向容器索要user对象
User u=(User)ac.getBean("user");
//3打印user对象
System.out.println(u);
}
}