准备工作:
(1)下载spring最新版本
下载后的压缩包为spring-3.2.0.M2-dist.zip,为spring3.2版本.
(2)下载commons-logging-1.1.1.jar文件,spring依赖这个jar,否则运行异常。
地址:http://commons.apache.org/logging/download_logging.cgi
下载后解压缩commons-logging-1.1.1-bin.zip,里面有需要的包。
1、新建一个java项目,导入spring需要的包
经过测试spring运行ioc最少导入以下4个包:
spring-core-3.2.0.M2.jar
spring-context-3.2.0.M2.jar
spring-beans-3.2.0.M2.jar
spring-expression-3.2.0.M2.jar
然后导入
commons-logging-1.1.1.jar
(导入包的过程:右键项目-build path-add libraries-user libraries-user libraries-new新建一个jar库-add external添加jar)
2、pojo(及javabean文件)Student.java
package com.ru.domain; public class Student { private Integer id; private String name; private Integer age; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
3、spring的配置文件:bean.xml
注:spring的配置文件样板可以在官方文档中查看,5.1. Introduction to the Spring IoC container and beans文档的第5章就是
配置了student,并且为student的属性赋了值
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="student" class="com.ru.domain.Student"> <!-- collaborators and configuration for this bean go here --> <property name="id" value="1"/> <property name="name" value="如神"/> <property name="age" value="23"/> </bean> </beans>
4、测试test.java
package com.ru.service; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.ru.domain.Student; public class Test1 { @Test public void test1(){ //ApplicationContext获取的是spring的beanFactory,从这里可以得到bean //加入beans.xml不再src目录下:new ClassPathXmlApplicationContext("com/ru/domain/beans.xml"); ApplicationContext ac=new ClassPathXmlApplicationContext("beans.xml"); Student stu=(Student)ac.getBean("student"); System.out.println("学生信息:"); System.out.println("学号:"+stu.getId()+"姓名:"+stu.getName()+"年龄:"+stu.getAge()); } }