1.导入jar包(此处用的是4.1.6版本)
spring各个版本的下载地址如下:
[http://repo.springsource.org/libs-release-local/org/springframework/spring/ ]
commons-logging-1.1.3.jar
spring-beans-4.1.6.RELEASE.jar
spring-context-4.1.6.RELEASE-javadoc.jar
spring-context-4.1.6.RELEASE.jar
spring-core-4.1.6.RELEASE.jar
spring-expression-4.1.6.RELEASE.jar
2.编写配置文件 applicationContext.xml 放入src目录下
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- student为你想要实例化的名字 com.ly.entity.Student为实体类对应的路径 prototype 为多例模式(可以不写,默认为单例模式 singleton) -->
<bean id="student" class="com.ly.entity.Student" scope="prototype">
</bean>
</beans>
3.编写实体类 Student
package com.ly.entity;
public class Student {
private Integer id;
private String name;
private User user;
public Student() {
super();
}
public Student(Integer id, String name) {
super();
this.id = id;
this.name = name;
}
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;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + "]";
}
}
4.编写测试类 StudentService
package com.ly.service;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.ly.entity.Student;
public class StudentService {
public static Student getStudent(){
//读取配置文件
ApplicationContext a = new ClassPathXmlApplicationContext("applicationContext.xml");
//获取配置文件中 bean标签 id 为student的类
Student stu = (Student)a.getBean("student");
//通过set方法 对stu进行赋值
stu.setId(123);
stu.setName("aa");
return stu;
}
public static void main(String[] args) {
Student stu = getStudent();
System.out.println(stu);
}
}
运行则可看到结果,一个简单的spring 框架搭建的工程完成。