Spring框架基础使用
1.简单介绍
有时候会将Spring容器称为 IOC 容器。 IOC也是Spring的两大核心功能之一。
两大核心功能(基石): IOC 和 AOP 。
IOC : inverse of control 控制反转。 将对象的创建权交由Spring容器来管理,它是一种目的。
DI: Dependecy Inject 依赖注入。是将一个对象所依赖的其他对象的实例传进来,它是一种手段。
注入的体现就是给成员变量赋值:1.构造方法传参 ;2.调用对象的setter方法
- 官网地址:https://spring.io/
- Spring框架的作用主要是由Spring容器负责对象的创建和销毁
针对web层的开发子模块是:SpringMVC - Spring的jar包下载地址:
https://repo.spring.io/release/org/springframework/spring
百度云下载地址:
链接:https://pan.baidu.com/s/1YHW459l_3g0G7Xpf4QLJcA
提取码:dr5a
2.添加依赖
以Spring 4.x 系列为例:
- 外部的jar包:
commons-logging (日志框架) - 最小化使用
- spring-beans-4.3.28.RELEASE.jar Spring 的Bean管理
- spring-context-4.3.28.RELEASE.jar Spring的上下文
- spring-core-4.3.28.RELEASE.jar Spring的核心
- spring-expression-4.3.28.RELEASE.jar Spring的表达式
3.创建Spring容器
Spring容器是一个管理对象(实例)的场所 , 它里面的对象的创建和销毁工作都由Spring容器来负责。
用户要做的事情就是告诉Spring容器管理哪些对象,以及对象之间的关系是什么。
类似于我们在 web.xml中配置Web组件。在Spring中,我们可以按照Spring的要求,在它的XML配置文件中作出声明即可。
Spring容器的接口由 ApplicationContext
来定义。
ClassPathXmlApplicationContext基于类路径下的Spring容器创建
public static void main(String[] args) {
ApplicationContext context = null;// 接口需要实现类的实例来赋值。
//实现类有很多:ClassPathXmlApplicationContext 是类路径下基于 XML配置的Spring容器的实现
// 它的一个构造方法(String),需要指定 配置文件的位置(基于类路径下的位置)。
context = new ClassPathXmlApplicationContext("com/example/spring/demo1.xml");
}
4.创建一个需要被spring管理的类
Student
public class Student {
private String name;
private Integer age;
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;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
5.创建Spring配置文件
<?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">
<!--在这个xml配置文件中就可以使用Spring提供的标签,来进行 对象(在Spring中有一个特殊的称呼:Bean)的 配置-->
<!--
要想让Spring 管理某个对象。需要使用 bean 标签
id 或 name 属性: 用于给bean起一个名字(需要容器中唯一)。如果不赋值,则自己无法从容器中取出来。
class 属性: 用于指定 bean 对应的Java类型(需要是完全限定名)。
-->
<bean id="myStudent" class="com.example.spring.Student"></bean>
</beans>
5.使用容器中的对象
/*
当使用带参数的构造方法来创建ClassPathXmlApplicationContext对象时, Spring容器会自动创建并启动。
在启动过程中,会将其负责管理的那些对象,进行实例化。
*/
/*
在后续的过程中,我们可以通过从Spring容器中获取对象的实例,来进行使用即可。
而不用关心对象是如何创建出来的(Spring的核心体现)
比如: 可以调用 容器的 getBean(String id) 方法来根据名称获取对象
*/
// Student myStudent = (Student) context.getBean("myStudent");
Student myStudent = context.getBean("myStudent", Student.class);
//调用对象的功能
System.out.println(myStudent);
打印结果: