Spring的使用

发布时间 2024-01-12 17:57:52作者: 司丝思

一、创建Spring项目

1、创建maven项目

2、引入spring框架依赖

<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>

3、添加启动类

二、存储、获取和使用Bean

1、存储Bean

1)创建Bean

spring中的Bean实际上就是Java中的普通对象

2)将Bean注册到spring容器中

在resources目录下创建.xml文件,将一下内容复制到.xml文件中(以下内容是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">

</beans>

将创建的User对象注入到spring容器中

2、获取Bean

1)创建spring上下文

可以使用ApplicationContext获得上下文对象

2)获取指定Bean对象

getBean()有很多重载的方法,下面介绍两种方法获取Bean。

先创建一个UserController类,并将其放在controller目录下

 上述这种方法是根据类型获取Bean,当一个类型被两次注入到spring-config.xml 中时,根据类型去获取Bean时,因为存在两个相同Bean,程序不知去获取哪一个,因此会报错,如下图:

另外一种方法时根据id,类型来获取Bean

当一个类型被两次注入到spring-config.xml 中时,可以根据id,类型的方法来获取Bean。