Spring Boot 2.0.0参考手册_中文版_Part III_13

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

Part III. 使用Spring Boot

这一节将会讲述关于应该如何使用Spring Boot的更多细节。它包括许多主题例如构建系统,自动配置和怎么运行自己的应用。我们也讲述一些Spring Boot的最佳实践。虽然没有关于Spring Boot非常特别的东西(它只是另一个你可以使用的库),但接下来的一些建议可以让你的开发过程更容易一点。

如果你刚开始学习Spring Boot,在学习这节之前你可能应该先阅读一下『Getting Started』部分。

13. 构建系统

强烈建议你选择一个支持依赖管理的构建系统,构建系统可以使用发布在『Maven Central』仓库中的工件。我们建议你选择Maven或Gradle。Spring Boot可能也可以与其它的构建系统进行协作(例如Ant),但不能特别好的支持其它的构建系统。

13.1 依赖管理

Spring Boot的每一次发布都会提供它支持的依赖列表。实际应用时,在你的构建配置中不需要提供这些依赖的版本,因为Spring Boot会帮你进行管理。当你升级Spring Boot时,这些依赖也会随之进行升级。

如果有必要的话,你仍可以指定版本并覆盖Spring Boot的推荐。

这个列表包含了所有你在Spring Boot中可以使用的Spring模块,也包含了第三方库的精制列表。这个列表可以当做一个标准可用的Bills of Materials (spring-boot-dependencies),也额外的专门支持Maven和Gradle可用。

Spring Boot的每一次发布都是与Spring框架的基本版本相关的,因此我们强烈建议你在自己使用时不要指定它的版本。

13.2 Maven

Maven用户可以继承spring-boot-starter-parent工程来获得合理的默认配置。父工程提供了下面的特性:

  • Java 1.6作为默认的编译级别。

  • UTF-8源码编码。

  • 依赖管理部分,对于常用的依赖允许你忽略<version>标签,从spring-boot-dependencies继承POM。

  • 合理的资源过滤。

  • 合理的插件配置(exec plugin, surefire, Git commit ID, shade)。

  • 对包括特定配置文件的application.propertiesapplication.yml的合理资源过滤(例如,application-foo.propertiesapplication-foo.yml)。

最后一点:由于默认配置文件采用Spring风格的占位符(${…​}),Maven过滤改成了使用@..@占位符(你可以使用Maven属性resource.delimiter来覆盖)。

13.2.1 继承starter parent

为了配置你的工程继承spring-boot-starter-parent,简单的设置parent

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

你应该只需要在这个依赖中指定Spring Boot的版本号。如果你导入额外的starters,你可以安全的忽略这个版本号。

有了这个设置,你也可以通过在你的工程中重写一个属性来覆盖单独的依赖。例如,为了升级另一个Spring Data的发布版本,你将需要在你的pom.xml中添加以下内容:

<properties>
    <spring-data-releasetrain.version>Fowler-SR2</spring-data-releasetrain.version>
</properties>

检查spring-boot-dependencies pom支持的属性清单。

13.2.2 没有父POM的情况下使用Spring Boot

不是每个人都喜欢继承spring-boot-starter-parent POM的。你也可以有需要使用的公司的标准父POM,或者你可能更喜欢显式的声明你所有的Maven配置。

如果你不想使用spring-boot-starter-parent,但你仍要保留依赖管理的好处(不是插件管理),你可以使用scope=import依赖:

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

这个设置不允许你使用上面阐述的属性来重写单独的依赖。为了取得同样的效果,你需要在spring-boot-dependencies入口之前在工程的dependencyManagement中的添加一个入口。为了升级另一个Spring Data的发布版本,你将需要在你的pom.xml中添加以下内容:

<dependencyManagement>
    <dependencies>
        <!-- Override Spring Data release train provided by Spring Boot -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-releasetrain</artifactId>
            <version>Fowler-SR2</version>
            <scope>import</scope>
            <type>pom</type>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>2.0.0.BUILD-SNAPSHOT</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

在上面的例子中,我们指定了一个POM但任何依赖类型都可以被重写。

13.2.3 更改Java版本

spring-boot-starter-parent选择了相当保守的Java兼容性。如果你想听从我们的建议,使用更新的Java版本,你可以添加java.version属性。

<properties>
    <java.version>1.8</java.version>
</properties>
13.2.4 使用Spring Boot Maven插件

Spring Boot包含了一个Maven插件,这个插件可以将工程打包为一个可执行的jar包。如果你向使用它的话,将它添加到你的<plugins>部分:

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

如果你想使用Spring Boot的starter parent pom,你只需要添加这个插件,不需要配置它,除非你想更改父POM中的定义的设置。

13.3 Gradle

Gradle用户可以直接在它们的dependencies部分导入starters。不像Maven,这儿不能导入“super parent”来共享一些配置。

apply plugin: 'java'

repositories {
    maven { url "http://repo.spring.io/snapshot" }
    maven { url "http://repo.spring.io/milestone" }
}

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web:2.0.0.BUILD-SNAPSHOT")
}

spring-boot-gradle-plugin也可用,并提供了从源码创建可执行jars和运行项目的功能。它也提供了依赖管理,在其它的兼容性之间,允许你忽略任何Spring Boot管理的依赖的版本号:

buildscript {
    repositories {
        maven { url "http://repo.spring.io/snapshot" }
        maven { url "http://repo.spring.io/milestone" }
    }

    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:2.0.0.BUILD-SNAPSHOT")
    }
}

apply plugin: 'java'
apply plugin: 'org.springframework.boot'

repositories {
    maven { url "http://repo.spring.io/snapshot" }
    maven { url "http://repo.spring.io/milestone" }
}

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web")
    testCompile("org.springframework.boot:spring-boot-starter-test")
}

13.4 Ant

使用Apache Ant+Ivy来创建一个Spring Boot项目是可能的。spring-boot-antlib “AntLib”模块也可以用来帮助Ant创建可执行jars。

为了声明依赖,一个典型的ivy.xml文件如下所示:

<ivy-module version="2.0">
    <info organisation="org.springframework.boot" module="spring-boot-sample-ant" />
    <configurations>
        <conf name="compile" description="everything needed to compile this module" />
        <conf name="runtime" extends="compile" description="everything needed to run this module" />
    </configurations>
    <dependencies>
        <dependency org="org.springframework.boot" name="spring-boot-starter"
            rev="${spring-boot.version}" conf="compile" />
    </dependencies>
</ivy-module>

一个典型build.xml如下所示:

<project
    xmlns:ivy="antlib:org.apache.ivy.ant"
    xmlns:spring-boot="antlib:org.springframework.boot.ant"
    name="myapp" default="build">

    <property name="spring-boot.version" value="1.3.0.BUILD-SNAPSHOT" />

    <target name="resolve" description="--> retrieve dependencies with ivy">
        <ivy:retrieve pattern="lib/[conf]/[artifact]-[type]-[revision].[ext]" />
    </target>

    <target name="classpaths" depends="resolve">
        <path id="compile.classpath">
            <fileset dir="lib/compile" includes="*.jar" />
        </path>
    </target>

    <target name="init" depends="classpaths">
        <mkdir dir="build/classes" />
    </target>

    <target name="compile" depends="init" description="compile">
        <javac srcdir="src/main/java" destdir="build/classes" classpathref="compile.classpath" />
    </target>

    <target name="build" depends="compile">
        <spring-boot:exejar destfile="build/myapp.jar" classes="build/classes">
            <spring-boot:lib>
                <fileset dir="lib/runtime" />
            </spring-boot:lib>
        </spring-boot:exejar>
    </target>
</project>

如果你不想使用spring-boot-antlib模块,请看79.10小节,“Build an executable archive from Ant without using spring-boot-antlib” “How-to”。

13.5 Starters

启动器是一系列你可以包含进自己应用中的实用依赖描述符。你可以得到所有Spring和你需要的相关技术的一站式服务,不需要有搜索样例代码和拷贝粘贴依赖描述符的负担。例如,如果你想开始使用Spring和JPA来进行数据库链接,只需要在你的工程中包含spring-boot-starter-data-jpa依赖,你便可以很好的前行了。

启动器包含许多你需要启动并快速运行一个工程的依赖,并持续支持一系列传递管理的依赖。

What’s in a name

所有的官方启动器都有一个类似的命名模式:spring-boot-starter-**是应用的特性类型。这个命名结构用来在你需要时帮助你发现一个启动器。Maven在许多IDEs中进行了集成,允许你通过名字来搜索依赖。例如,安装了合适的Eclipse或STS插件,你可以简单的在POM编辑器中点击ctrl-space并输入“spring-boot-starter”来查找一个完整的列表。

正如在创建你自己的启动器部分讲述的那样,第三方启动器不应该与spring-boot一起启动,因为它是预留给官方Spring Boot构建的。acme的第三方启动器通过命名为acme-spring-boot-starter

下面的应用启动器由Spring Boot提供,在org.springframework.boot组下:

表13.1. Spring Boot应用启动器

NameDescriptionPOM
spring-boot-starter-thymeleafStarter for building MVC web applications using Thymeleaf viewsPOM
spring-boot-starter-data-couchbaseStarter for using Couchbase document-oriented database and Spring Data CouchbasePOM
spring-boot-starter-artemisStarter for JMS messaging using Apache ArtemisPOM
spring-boot-starter-web-servicesStarter for using Spring Web ServicesPOM
spring-boot-starter-mailStarter for using Java Mail and Spring Framework’s email sending supportPOM
spring-boot-starter-data-redisStarter for using Redis key-value data store with Spring Data Redis and the Jedis clientPOM
spring-boot-starter-webStarter for building web, including RESTful, applications using Spring MVC. Uses Tomcat as the default embedded containerPOM
spring-boot-starter-data-gemfireStarter for using GemFire distributed data store and Spring Data GemFirePOM
spring-boot-starter-activemqStarter for JMS messaging using Apache ActiveMQPOM
spring-boot-starter-data-elasticsearchStarter for using Elasticsearch search and analytics engine and Spring Data ElasticsearchPOM
spring-boot-starter-integrationStarter for using Spring IntegrationPOM
spring-boot-starter-testStarter for testing Spring Boot applications with libraries including JUnit, Hamcrest and MockitoPOM
spring-boot-starter-jdbcStarter for using JDBC with the Tomcat JDBC connection poolPOM
spring-boot-starter-mobileStarter for building web applications using Spring MobilePOM
spring-boot-starter-validationStarter for using Java Bean Validation with Hibernate ValidatorPOM
spring-boot-starter-hateoasStarter for building hypermedia-based RESTful web application with Spring MVC and Spring HATEOASPOM
spring-boot-starter-jerseyStarter for building RESTful web applications using JAX-RS and Jersey. An alternative to spring-boot-starter-webPOM
spring-boot-starter-data-neo4jStarter for using Neo4j graph database and Spring Data Neo4jPOM
spring-boot-starter-websocketStarter for building WebSocket applications using Spring Framework’s WebSocket supportPOM
spring-boot-starter-aopStarter for aspect-oriented programming with Spring AOP and AspectJPOM
spring-boot-starter-amqpStarter for using Spring AMQP and Rabbit MQPOM
spring-boot-starter-data-cassandraStarter for using Cassandra distributed database and Spring Data CassandraPOM
spring-boot-starter-social-facebookStarter for using Spring Social FacebookPOM
spring-boot-starter-jta-atomikosStarter for JTA transactions using AtomikosPOM
spring-boot-starter-securityStarter for using Spring SecurityPOM
spring-boot-starter-mustacheStarter for building MVC web applications using Mustache viewsPOM
spring-boot-starter-data-jpaStarter for using Spring Data JPA with HibernatePOM
spring-boot-starterCore starter, including auto-configuration support, logging and YAMLPOM
spring-boot-starter-groovy-templatesStarter for building MVC web applications using Groovy Templates viewsPOM
spring-boot-starter-freemarkerStarter for building MVC web applications using FreeMarker viewsPOM
spring-boot-starter-batchStarter for using Spring BatchPOM
spring-boot-starter-social-linkedinStater for using Spring Social LinkedInPOM
spring-boot-starter-cacheStarter for using Spring Framework’s caching supportPOM
spring-boot-starter-data-solrStarter for using the Apache Solr search platform with Spring Data SolrPOM
spring-boot-starter-data-mongodbStarter for using MongoDB document-oriented database and Spring Data MongoDBPOM
spring-boot-starter-jooqStarter for using jOOQ to access SQL databases. An alternative to spring-boot-starter-data-jpa or spring-boot-starter-jdbcPOM
spring-boot-starter-jta-narayanaSpring Boot Narayana JTA StarterPOM
spring-boot-starter-cloud-connectorsStarter for using Spring Cloud Connectors which simplifies connecting to services in cloud platforms like Cloud Foundry and HerokuPOM
spring-boot-starter-jta-bitronixStarter for JTA transactions using BitronixPOM
spring-boot-starter-social-twitterStarter for using Spring Social TwitterPOM
spring-boot-starter-data-restStarter for exposing Spring Data repositories over REST using Spring Data RESTPOM

除了应用启动器之外,下面的启动器可以用来添加产品准备功能:

Table 13.2. Spring Boot 产品启动器

NameDescriptionPom
spring-boot-starter-actuatorStarter for using Spring Boot’s Actuator which provides production ready features to help you monitor and manage your applicationPom

最后,如果你想排除或交换特定的技术方面,Spring Boot也包括一些可以使用的启动器:

Table 13.3. Spring Boot 技术启动器

NameDescriptionPom
spring-boot-starter-undertowStarter for using Undertow as the embedded servlet container. An alternative to spring-boot-starter-tomcatPom
spring-boot-starter-jettyStarter for using Jetty as the embedded servlet container. An alternative to spring-boot-starter-tomcatPom
spring-boot-starter-loggingStarter for logging using Logback. Default logging starterPom
spring-boot-starter-tomcatStarter for using Tomcat as the embedded servlet container. Default servlet container starter used by spring-boot-starter-webPom
spring-boot-starter-log4j2Starter for using Log4j2 for logging. An alternative to spring-boot-starter-loggingPom

对于额外的社区共享的启动器,请看GitHub上the spring-boot-starters模块的README file

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值