Spring框架简介

Spring是Java开发中至关重要的应用程序开发框架。Spring的核心功能是IoC容器、依赖注入和简化的AOP编程模型,依据这些核心特性,Spring发展出了一个庞大的生态,比如用于Web开发的SpringMVC,微服务的全套解决方案SpringCloud,以及负责整个Spring项目整合配置的SpringBoot等。我们日常Java开发中不可避免的会用到Spring框架,我们不仅要掌握Spring框架的用法,也要能够基于Spring扩展自己的功能,因此也必须了解框架的内部原理。

本系列笔记我们将以最新的Spring 6版本为例,详细介绍Spring框架的方方面面。

引入Maven依赖

Spring框架对自身做了详细的拆分,其中有3个核心依赖通常都是必须引入的。

  • spring-core:框架的基础类
  • spring-context:容器上下文相关功能
  • spring-beans:Bean装配相关功能
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>6.2.17</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>6.2.17</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
    <version>6.2.17</version>
</dependency>

注:Spring框架本身也在快速迭代,我这里使用的是6.2.17版本,实际使用的依赖版本可能与以上不同。

除了核心依赖,Spring内部还依赖SLF4J进行日志输出,SLF4J实际上只是一组接口,我们还需要具体的日志实现库,比较常用的是Logback,因此我们还需要引入以下依赖。

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>2.0.17</version>
</dependency>
<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.5.32</version>
</dependency>

启动Spring容器

首先我们要知道,启动Spring需要一组配置,比较传统的方式是使用XML配置文件,此外如果使用SpringBoot则推荐使用JavaConfig,两者是等同的,下面是一个XML配置文件。配置文件会定义Spring框架需要的参数以及需要加载的Bean信息等,我们这里先留空。大部分基于Spring或是与Spring进行整合的其他框架都是通过配置Spring Bean作为整个框架启动的入口。

applicationContext.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"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
</beans>

对于基于Servlet的Web工程,Spring一般通过配置Listener组件的方式启动,我们将在后文详细介绍。如果是普通Java工程,则需要我们使用类似如下代码手动启动。

ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

上面代码中,我们通过加载classpath下的applicationContext.xml配置文件方式启动了Spring上下文。

如果正确的配置了日志框架,我们可以看到类似如下的DEBUG输出。

12:15:26.588 [main] DEBUG org.springframework.context.support.ClassPathXmlApplicationContext -- Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@77e9807f
12:15:26.840 [main] DEBUG org.springframework.beans.factory.xml.XmlBeanDefinitionReader -- Loaded 0 bean definitions from class path resource [applicationContext.xml]
作者:Gacfox
版权声明:本网站为非盈利性质,文章如非特殊说明均为原创,版权遵循知识共享协议CC BY-NC-ND 4.0进行授权,转载必须署名,禁止用于商业目的或演绎修改后转载。