SpringBoot基础的依赖说明


前言

前阵子,为了赶进度,项目在构建的时候,没有仔细研究相关依赖的特性、用处,而是囫囵吞枣,这边copy一点,那边copy一点,结果被大佬问及相关依赖的作用时,就死机了,实在不应该,项目再赶,也需要挤时间去了解。


前提

官网给出的推荐如下,但我的maven为3.0.X版本,截止目前还没遇到过什么差错。

  1. JDK 1.8 or later
  2. Gradle 4+ or Maven 3.2+

官网连接


spring-boot-starter-parent

The spring-boot-starter-parent project is a special starter project – that provides default configurations for our application and a complete dependency tree to quickly build our Spring Boot project. It also provides default configuration for Maven plugins such as maven-failsafe-plugin, maven-jar-plugin, maven-surefire-plugin, maven-war-plugin. Beyond that, it also inherits dependency management from spring-boot-dependencies which is the parent to the spring-boot-starter-parent.

这个依赖是最常见的,通常用作父模块的依赖,来构建一个包含多个子模块的SpringBoot应用。在官网的解释中,它提供Springboot的默认配置,和一棵完整的SpringBoot依赖树,还包括maven的打包插件。

通过spring-boot-starter-parent依赖,在各个子模块中,我们引申的各个SpringBoot依赖甚至连版本号都可以省略,只需要指定spring-boot-starter-parent的依赖。此时,子模块的各个SpringBoot依赖会默认为父依赖中的版本。

<!-- Inherit defaults from Spring Boot -->
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.2.RELEASE</version>
</parent>

这里,有人可能不喜欢引用spring-boot-starter-parent来拓展各个子模块,也有人是因为需要继承自己的父模块,而maven又不允许有多个“父类”,在官网,它也给出了解决方案:

<dependencyManagement>
    <dependencies>
        <dependency>
            <!-- Import dependency management from Spring Boot -->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>2.2.2.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

通过<scope>import</scope>标签,导入spring-boot-dependencies依赖,其实就一个pom文件,该pom文件又通过<dependencyManagement>标签去寻找各个SpringBoot相关依赖,就可以达到相同的效果。


spring-boot-starter-web

以spring-boot-starter-web:2.0.1.RELEASE版本为例子,它包含的依赖如下:

  1. spring-boot-starter:2.0.1.RELEASE
Spring Boot的核心启动器,包含了自动配置、日志和YAML
  1. spring-boot-starter-json:2.0.1.RELEASE
Spring Boot 提供了 Jackson 的自动配置,而JackJson来源于 spring-boot-
starter-json这个包
  1. spring-boot-starter-tomcat:2.0.1.RELEASE

SpringBoot封装了Tomcat,并把它作为默认的容器,当然,我们也可以进行修改为jetty,两者都是作为servlet容器,据说jetty在长连接上比较具有优势:

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jetty</artifactId>
        </dependency>
    </dependencies>
  1. hibernate-validator:6.0.9.Final

查看文档

一个验证器,它可以帮我们验证一些参数的格式,譬如是否为空,是否为手机格式。
  1. spring-web:5.0.5.RELEASE

从给出的文档中,我们可以知道,该模块会进行IOC容器的初始化工作,而且提供了其他的Web框架和HTTP技术。

  1. spring-webmvc:5.0.5.RELEASE

spring-webmvc则是在spring-web上的进一步延伸,其实从依赖也可以看出,两者引入的依赖有重复的部分,spring-webmvc是Spring MVC的实现,如果我们不想用springMVC而只是用到其他web相关的技术,那我们可以在引入的时候将这个依赖排除。

The Web layer consists of the spring-web, spring-webmvc, spring-
websocket, and spring-webmvc-portlet modules.

The spring-web module provides basic web-oriented integration 
features such as multipart file upload functionality and the 
initialization of the IoC container using Servlet listeners and 
a web-oriented application context. It also contains an HTTP client
and the web-related parts of Spring’s remoting support.

The spring-webmvc module (also known as the Web-Servlet module) 
contains Spring’s model-view-controller (MVC) and REST Web 
Services implementation for web applications. Spring’s MVC framework 
provides a clean separation between domain model code and web 
forms and integrates with all of the other features of the 
Spring Framework.

The spring-webmvc-portlet module (also known as the Web-Portlet 
module) provides the MVC implementation to be used in a 
Portlet environment and mirrors the functionality of the Servlet-based
spring-webmvc module.

文档查看


spring-boot-configuration-processor

关于这个依赖,有点玄学,首先,我可以肯定关于的数据源的配置是没有问题的,我的mapper接口、xml也都是正确无误的,而我的数据源配置在了yml文件中,springboot本身默认的读取文件格式就包含了yml文件,这怎么就报错了??

15:19:25.150 org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'XXXController':
Error creating bean with name 'XXXChainMapper' defined in file: 
Unsatisfied dependency expressed through method 'sqlSessionFactory' 
parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Failed to determine a suitable driver class
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
15:19:25.262 [main] ERROR o.s.b.d.LoggingFailureAnalysisReporter - 
***************************
APPLICATION FAILED TO START
***************************
Description:
Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified and no embedded datasource could be auto-configured.

通过对比之前的项目,我发现现在的项目中莫名其妙的多出这个依赖,于是在试着把它删除之后,竟然神奇的解决了这个bug。问题到这儿还没结束,当我写篇文章的时候,想着重新复现这个问题的时候,又重新将这个依赖加回去时,发现尽然没报错了!!!what?查看了一下类路径,配置文件这时都被加载进去了??即使clean了一遍,重新运行也任然ok,百思不得解。

结合官方的文档,我们可以知道,这个依赖的作用是:可以通过注解的方式来配置元数据(数据源?)。通过这个包,我们还可以在在类中构造配置信息,不过这种方式个人不太感冒,它让整个项目结构变得有、乱,也不容易修改和拓展。目前项目里头这个依赖已经都去掉了。

You can easily generate your own configuration metadata file from 
items annotated with @ConfigurationProperties by using the spring-
boot-configuration-processor jar. The jar includes a Java annotation 
processor which is invoked as your project is compiled. To use the 
processor, include a dependency on spring-boot-configuration-
processor.

mybatis-spring-boot-starter

项目里头的持久层用的mybatis(也可以是mybatis-plus、hibernate等),所以还要引入这个依赖。现在的mybatis不用像老版本那样用很多“累赘”的xml文件进行配置,而是提供了注解的方式,也支持逆向工程,从而提高开发效率。

mybatis-spring官网文档


druid-spring-boot-starter

数据库连接池采用的是druid,口碑不错,提供了SQL级别的可视化监控工具,只支持JDK 6以上版本,更多详细文档请移至官方文档链接:跳转

附带一些配置和说明

# 申明数据源
spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    url: 
    username: 
    password: 
    driverClassName: com.mysql.jdbc.Driver
    #初始化时建立物理连接的个数。初始化发生在显示调用init方法,或者第一次getConnection时
    initialSize: 5
    #最小连接池数量
    minIdle: 5
    #最大连接池数量
    maxActive: 20
    #获取连接时最大等待时间,单位毫秒。配置了maxWait之后,缺省启用公平锁,并发效率会有所下降,
    #如果需要可以通过配置useUnfairLock属性为true使用非公平锁。
    maxWait: 60000
    #Destroy线程会检测连接的间隔时间
    #testWhileIdle的判断依据
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    #用来检测连接是否有效的sql
    validationQuery: SELECT 1
    #建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于
    #timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。
    testWhileIdle: true
    #申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。
    testOnBorrow: false
    #归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。
    testOnReturn: false
    #是否缓存preparedStatement,也就是PSCache。PSCache对支持游标的数据库性能提升巨大,
    #比如说oracle。在mysql下建议关闭。
    poolPreparedStatements: true
    #当数据库抛出一些不可恢复的异常时,抛弃连接
    exceptionSorter: true
    #属性类型是字符串,通过别名的方式配置扩展插件,常用的插件有:
    #监控统计用的filter:stat
    #日志用的filter:log4j
    #防御sql注入的filter:wall
    filters: stat,wall,log4j
    #要启用PSCache,必须配置大于0,当大于0时,poolPreparedStatements自动触发修改为true。
    #在Druid中,不会存在Oracle下PSCache占用内存过多的问题,可以把这个数值配置大一些,比如说100
    maxPoolPreparedStatementPerConnectionSize: 20
    #通过connectProperties属性来打开mergeSql功能;慢SQL记录
    #合并执行的相同sql,避免因为参数不同而统计多条sql语句
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
    #合并多个DruidDataSource的监控数据
    useGlobalDataSourceStat: true

Demo

github自取

相关配置说明

<build>
        <!--配置打包后名字-->
        <finalName>web1-service</finalName>
        <resources>
            <resource>
                <!--配置可被访问的资源的位置,不像被访问到如环境配置可用excludes标签-->
                <directory>src/main/resources</directory>
                <includes>
                    <include>application.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <excludes>
                    <exclude>env/**</exclude>
                </excludes>
                <filtering>false</filtering>
            </resource>
            <!--加载的环境配置默认是profiles.active指向的文件-->
            <resource>
                <directory>src/main/resources/env/${profiles.active}</directory>
            </resource>
        </resources>
        <!--配置springBoot打包插件-->
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <jvmArguments>-Dfile.encoding=UTF-8</jvmArguments>
                    <mainClass>com.web1.Web1ServerApplication</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                        <!--可以把依赖的包都打包到生成的Jar包中 -->
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
      <!--如果在开发一个库,直接使用默认的maven-jar-plugin插件即可;-->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <configuration>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>
  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

legendaryhaha

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值