1.环境配置
Eclipse的STS插件:https://spring.io/tools3/sts/all
Spring所有的包:http://repo.spring.io/release/org/springframework/spring/
需要用到的jar包(5+1),将下列包导入到项目中
- spring-aop-4.3.9.RELEASE.jar 开发AOP特性时需要的Jar包
- spring-beans-4.3.9.RELEASE.jar 处理Bean的Jar包
- spring-context-4.3.9.RELEASE.jar 处理Spring上下文的Jar包
- spring-core-4.3.9.RELEASE.jar Spring核心
- spring-expression-4.3.9.RELEASE.jar Spring表达式
还有第三方提供的日志Jar包
- commons-logging-1.2.jar
2.编写配置文件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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 通过bean来给类中的属性赋值
id:唯一标识符
class:实体类的位置 包名+类名
property:该class类代表的属性值
name:属性名
value:值
-->
<bean id="student1" class="com.zy.pojo.Student">
<property name="stuNo" value="8"></property>
<property name="stuName" value="uu"></property>
<property name="stuClass" value="2"></property>
</bean>
</beans>
3.创建实体类Student.java
package com.zy.pojo;
public class Student {
private Integer stuNo;
private String stuName;
private String stuClass;
public Student(Integer stuNo, String stuName, String stuClass) {
super();
this.stuNo = stuNo;
this.stuName = stuName;
this.stuClass = stuClass;
}
public Student() {
super();
}
public Integer getStuNo() {
return stuNo;
}
public void setStuNo(Integer stuNo) {
this.stuNo = stuNo;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public String getStuClass() {
return stuClass;
}
public void setStuClass(String stuClass) {
this.stuClass = stuClass;
}
@Override
public String toString() {
return "Student [stuNo=" + stuNo + ", stuName=" + stuName + ", stuClass=" + stuClass + "]";
}
}
4.测试类StudentTest.java
package com.zy.test;
import java.applet.AppletContext;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.zy.pojo.Student;
public class StudentTest {
public static void main(String[] args) {
// 传统赋值方式
Student student1 = new Student();
student1.setStuNo(5);
student1.setStuName("王五");
student1.setStuClass("3");
System.out.println(student1);
/**
* 使用Spring IOC容器外部注入,控制反转(依赖注入)
*/
// ApplicationContext:获取Spring上下文
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
// 通过id来找到bean
Student student2 = (Student) ac.getBean("student1");
System.out.println(student2);
}
}
5.运行结果
6.项目结构
解析:
- Spring 使用Ioc容器来装类中的属性值,相当于new一个对象再赋值