Spring项目的创建和使用(一)
一、什么是 Spring
🐻🐻🐻 简单来说,Spring 就是包含了众多⼯具⽅法的 IoC 容器。
二、创建 Spring 项目
🌐2.1 创建⼀个 Maven 项⽬。
🌐2.2 引入 Spring 框架所需的依赖(spring-context、spring-beans),可以去 Maven 中央仓库下载,也可以直接复制下面代码。
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
</dependencies>
在 pom.xml 文件中粘贴进去,然后重新刷新 Maven 项目,spring-context 表示 spring 上下⽂, spring-beans 表示 spring 对象。 🌐2.3 创建启动类。 在 Java 包下创建一个名为 Main 的 类,命名没有要求,里面包含 main 方法就行。
public class Main {
public static void main(String[] args) {
}
}
三、存储 Bean 对象
🌐3.1 创建 Bean 对象 Bean 对象其实就是 Java 的类对象,创建 com.meng.Student类。
public class Student {
public String name = "貂蝉";
public void school() {
System.out.println(name + " 正在上课");
}
}
🌐3.2 注入 Bean 对象 在 resources 资源包下创建一个 spring-config.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">
</beans>
将 Student 对象注册到 spring 容器里面即可。
🌐3.3 使用 Bean 对象, 在启动类里面进行使用。 (1) 获取 spring 上下文
ApplicationContext context =
new ClassPathXmlApplicationContext("spring-config.xml");
有些资料里使用 BeanFactory 也可以获取 spring 上下文,但它们的区别是:
-
ApplicationContext 是 BeanFactory的子类,它可以实现 BeanFactory 的所有功能,并且还有扩充了国际化支持,资源访问支持…… ApplicationContext 是一次加载所有的 Bean 对象, BeanFactory 是需要那个 Bean 对象才会去加载。 综上所述,ApplicationContext 更加推荐使用。
(2) getBean 的常见方法
Student student = (Student) context.getBean("student");
student.school();
Student student1 = context.getBean(Student.class);
student1.school();
Student student2 = context.getBean("student",Student.class);
student2.school();
-
可以直接使用注册 Bean 对象时的 id 名来获取,但是返回类型是 Object , 需要转换类型。 可以直接使用一个 Class 参数来获取,不需要转换类型。 可以同时使用 Bean id 和 Class 参数来获取,更推荐使用。
总结:当前注册 Bean 对象时,我们还是需要一个一个注册,使用注解的方式会更加简单,这也是spring发展的历程,下期让我们再分享 spring 更加简单的存储和读取对象方法。
