Spring容器是什么(浅显易懂)?

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34598667/article/details/83245753

Spring容器是什么?


概述

Spring容器到底是什么?

从概念上讲:Spring 容器是 Spring 框架的核心,是用来管理对象的。容器将创建对象,把它们连接在一起,配置它们,并管理他们的整个生命周期从创建到销毁。

从具象化讲:通过概念的描述有些同学还是一脸懵逼,在我们的项目中哪个东西是Spring容器?在java项目中,我们使用实现了org.springframework.context.ApplicationContext接口的实现类。在web项目中,我们使用spring.xml——Spring的配置文件。

从代码上讲:一个Spring容器就是某个实现了ApplicationContext接口的类的实例。也就是说,从代码层面,Spring容器其实就是一个ApplicationContext(一个实例化对象)。


Spring配置文件简介

通过上面的描述大家应该也有了一定的认知,我们此以web项目为例,为大家讲述spring.xml
首先,spring配置文件内容如下:

[html] view plaincopy
<?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=“…”>  
    <!– 这里写bean的配置 >  
  </bean>  
  
  <!– 在此可以定义更多的bean >  
  
</beans>  

我们可以在xml中配置一系列我们需要的bean,配置之后Spring就会按照我们配置的东西进行解析,从而得到我们需要的值。


实例化Spring容器

PS:此内容上一章节演示过,这里只提供方式,需要操作的同学可查看上一章节

Spring容器类型

Spring提供了两种不同的类型的容器
Spring BeanFactory容器:它是最简单的容器,给 DI 提供了基本的支持
ApplicationContext容器 :ApplicationContext 容器继承自BeanFactory,它包括 BeanFactory 容器的所有功能,所以通常建议使用。

ApplicationContext容器

实例化此Spring容器常用的两种方式:
方法一:在类路径下寻找配置文件来实例化容器。

ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{"spring.xml"});

方法二:在文件系统路径下寻找配置文件来实例化容器。

ApplicationContext ctx = new FileSystemXmlApplicationContext(new String[]{"d:\\beans.xml"});

本章简述了一下Spring容器,下章详解Spring容器对bean的管理:
https://blog.csdn.net/qq_34598667/article/details/83246492

猜你喜欢

转载自blog.csdn.net/qq_34598667/article/details/83245753