网站做个seo要多少钱,海阳市住房和城乡建设局官方网站,asp购物网站,电脑系统优化软件排行榜文章目录 一. 创建 Spring 项目1.1 创建一个Maven项目1.2 添加Spring依赖1.4. 创建一个启动类 二. 将 Bean 对象存放至 Spring 容器中三. 从 Spring 容器中读取到 Bean1. 得到Spring对象2. 通过Spring 对象getBean方法获取到 Bean对象【DI操作】 一. 创建 Spring 项目
接下来使… 文章目录 一. 创建 Spring 项目1.1 创建一个Maven项目1.2 添加Spring依赖1.4. 创建一个启动类 二. 将 Bean 对象存放至 Spring 容器中三. 从 Spring 容器中读取到 Bean1. 得到Spring对象2. 通过Spring 对象getBean方法获取到 Bean对象【DI操作】 一. 创建 Spring 项目
接下来使⽤ Maven ⽅式来创建⼀个 Spring 项⽬创建 Spring 项⽬和 Servlet 类似总共分为以下 3步
创建⼀个普通 Maven 项⽬。添加 Spring 框架⽀持spring-context、spring-beans。添加启动类。
1.1 创建一个Maven项目
此处使用的IDEA版本为2021.3.2. 注意:项目名称中不能有中文.
1.2 添加Spring依赖
配置Maven国内源. IDEA设置文件有两个(一个是当前项目配置文件,新项目配置文件).需要设置这两个配置文件的国内源. 当前项目配置文件: 配置settings.xml至C:\Users\xxxflower\.m2中. 使用VScode打开文件.
新项目的配置文件: 方法同上设置新项目的配置文件.
重新下载jar包.(可无) 清空删除本地所有的jar包. 添加Spring依赖 在Maven中央仓库中搜索 Spring,点击5.x.x版本复制到pom.xml中.重新reload
1.4. 创建一个启动类 二. 将 Bean 对象存放至 Spring 容器中
创建一个bean.(在Java中一个对象如果被使用多次,就可以称之为Bean) 将Bean存储到Spring容器中
三. 从 Spring 容器中读取到 Bean
1. 得到Spring对象
想要从 Spring 中将Bean对象读取出来先要得到 Spring 上下文对象相当于得到了 Spring 容器。再通过 spring 上下文对象提供的方法获取到需要使用的Bean对象最后就能使用Bean对象了。 ApplicationContext也称为控制反转IoC容器是 Spring 框架的核心。
实现类描述ClassPathXmlApplicationContext常用加载类路径下的配置文件要求配置文件必须在类路径下FileSystemXmlApplicationContext可以加载磁盘任意路径下的配置文件必须要有访问权限AnnotationContigApplicationContext用于读取注解创建容器
package demo;public class Student {public Student() {System.out.println(Student 已加载);}public void sayHi(String name) {System.out.println(Hello name);}
}
package demo;public class Teacher {public Teacher() {System.out.println(Teacher 已加载);}public void sayHi(String name) {System.out.println(Hello name );}
}import demo.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class App {public static void main(String[] args) {//1.得到 SpringApplicationContext context new ClassPathXmlApplicationContext(spring-config.xml);
}运行结果: 程序启动ApplicationContext创建时会将所有的Bean对象都构造类似于饿汉的方式。
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;public class App2 {public static void main(String[] args) {// 1. 得到 bean 工厂BeanFactory factory new XmlBeanFactory(new ClassPathResource(spring-config.xml));}
}
运行结果 程序启动在BeanFactory创建时结果中没有如何输出只要不去获取使用Bean就不会去加载类似于懒汉的方式。
2. 通过Spring 对象getBean方法获取到 Bean对象【DI操作】
获取getBean的三种方式:
根据Bean的名字来获取
Student student (Student) context.getBean(student);此时返回的是一个Object对象需要我们去进行强制类型转换。
根据Bean类型获取
Student student context.getBean(Student.class);这种方式当beans中只有一个类的实例没有问题但是个有多个同类的实例会有问题即在 Spring 中注入多个同一个类的对象就会报错。 抛出了一个NoUniqueBeanDefinitionException异常,这表示注入的对象不是唯一的.
根据名称 类型获取
Student student context.getBean(student,Student.class);运行结果: 相比方式1更好,也是较为常用的方法.