添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
  • 尝试使用How to文档。它们提供常规的解决方法。
  • 学习Spring的基础知识,Spring Boot建立在它们之上。查阅Spring.io网站获取丰富的资料。
  • 在StackOverflow提问,我们监视Spring-Boot为标签的问题。
  • 在github.com/spring-projects/spring-boot/issues上报告错误。
  • 构建系统:Maven | Gradle | ant|Starters
    最佳实践:代码结构| @Configuration | @EnableAutoConfiguration | bean以及相关依赖注入
    运行您的代码IDE |Packaged | Maven | Gradle
    打包你的应用程序:生产Jar
    Spring Boot CLI:使用CLI

    5.学习Spring Boot特性

    需要更多关于Spring Boot核心功能的细节? 以下内容适合您:

    核心特性:SpringApplication | 外部配置| 配置文件|日志
    Web应用程序:MVC | 嵌入式容器
    使用数据:SQL |NO-SQL
    消息:概述|JMS
    测试:概述| 启动应用程序|utils
    扩展:自动配置| @条件

    6.转向生产

    当你准备把你的Spring Boot应用程序投入生产时,我们有一些你可能会喜欢的技巧:

    管理端点:概览|定制
    连接选项:HTTP |JMX
    监测:指标|
    审计 | 追踪| 处理

    7.高级主题

    最后,我们有更多高级用户的一些话题:

    Spring Boot应用程序部署:云部署| OS服务
    构建工具插件:Maven |gradle
    附录:应用程序属性| 自动配置类| 可执行的jars

    Part II.入门

    为所有Spring开发提供一个更快,更广泛的入门体验。
    开箱即用,但是随着需求开始偏离默认值,快速退出。
    提供大量项目(如嵌入式
    服务器 ,安全性,指标,运行状况检查和外部配置)通用的一系列非功能性功能。
    绝对不会生成代码,也不需要XML配置。

    9.系统要求

    Spring Boot 2.0.0.BUILD-SNAPSHOT需要Java 8和Spring Framework 5.0.2.RELEASE或更高版本。 为Maven 3.2+和Gradle 4提供了明确的构建支持。

    9.1.Servlet容器

    开箱即用支持以下嵌入式servlet容器:

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>com.example</groupId>
        <artifactId>myproject</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <!-- 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>
        <!-- Add typical dependencies for a web application -->
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
        </dependencies>
        <!-- Package as an executable jar -->
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
        <!-- Add Spring repositories -->
        <!-- (you don't need this if you are using a .RELEASE version) -->
        <repositories>
            <repository>
                <id>spring-snapshots</id>
                <url>http://repo.spring.io/snapshot</url>
                <snapshots><enabled>true</enabled></snapshots>
            </repository>
            <repository>
                <id>spring-milestones</id>
                <url>http://repo.spring.io/milestone</url>
            </repository>
        </repositories>
        <pluginRepositories>
            <pluginRepository>
                <id>spring-snapshots</id>
                <url>http://repo.spring.io/snapshot</url>
            </pluginRepository>
            <pluginRepository>
                <id>spring-milestones</id>
                <url>http://repo.spring.io/milestone</url>
            </pluginRepository>
        </pluginRepositories>
    </project>
    jcenter() 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' apply plugin: 'io.spring.dependency-management' jar { baseName = 'myproject' version = '0.0.1-SNAPSHOT' repositories { jcenter() 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" )

    10.2安装Spring Boot CLI

    Spring Boot CLI(命令行界面)是一个命令行工具,您可以使用它来快速使用Spring进行原型开发。 它可以让你运行Groovy脚本,这意味着你有一个熟悉的类Java语法,没有太多的样板代码。

    您不需要使用CLI来与Spring Boot一起工作,但这绝对是让Spring应用程序起飞的最快捷方式。

    10.2.1手动安装

    您可以从Spring软件存储库下载Spring CLI发行版:

    $ sdk install springboot dev /path/to/spring-boot/spring-boot-cli/target/spring-boot-cli-2.0.0.BUILD-SNAPSHOT-bin/spring-2.0.0.BUILD-SNAPSHOT/
    $ sdk default springboot dev
    $ spring --version
    Spring CLI v2.0.0.BUILD-SNAPSHOT

    前面的说明安装了一个名为dev实例的spring的本地实例。 它指向你的目标构建位置,所以每当你重建Spring Boot时,spring都是最新的。

    您可以通过运行以下命令来查看它:

    $ sdk ls springboot
    ================================================================================
    Available Springboot Versions
    ================================================================================
    > + dev
    * 2.0.0.BUILD-SNAPSHOT
    ================================================================================
    + - local version
    * - installed
    > - currently in use
    ================================================================================

    10.2.3 OSX Homebrew安装

    如果您在Mac上并使用 Homebrew ,则可以使用以下命令来安装Spring Boot CLI:
    Homebrew 安装 spring /usr/local/bin .

    $ . ~/.sdkman/candidates/springboot/current/shell-completion/bash/spring
    $ spring <HIT TAB HERE>
      grab  help  jar  run  test  version
    $ java -version
    java version "1.8.0_102"
    Java(TM) SE Runtime Environment (build 1.8.0_102-b14)
    Java HotSpot(TM) 64-Bit Server VM (build 25.102-b14, mixed mode)
    $ mvn -v
    Apache Maven 3.3.9 (bb52d8502b132ec0a5a3f4c09453c07478323dc5; 2015-11-10T16:41:47+00:00)
    Maven home: /usr/local/Cellar/maven/3.3.9/libexec
    Java version: 1.8.0_102, vendor: Oracle Corporation
    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>com.example</groupId>
        <artifactId>myproject</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.0.0.BUILD-SNAPSHOT</version>
        </parent>
        <!-- Additional lines to be added here... -->
        <!-- (you don't need this if you are using a .RELEASE version) -->
        <repositories>
            <repository>
                <id>spring-snapshots</id>
                <url>http://repo.spring.io/snapshot</url>
                <snapshots><enabled>true</enabled></snapshots>
            </repository>
            <repository>
                <id>spring-milestones</id>
                <url>http://repo.spring.io/milestone</url>
            </repository>
        </repositories>
        <pluginRepositories>
            <pluginRepository>
                <id>spring-snapshots</id>
                <url>http://repo.spring.io/snapshot</url>
            </pluginRepository>
            <pluginRepository>
                <id>spring-milestones</id>
                <url>http://repo.spring.io/milestone</url>
            </pluginRepository>
        </pluginRepositories>
    </project>

    上面的列表应该给你一个工作构建。 你可以通过运行mvn软件包来测试它(现在,你可以忽略“jar将是空的 - 没有内容被标记为包含!”警告)。

    < dependency > < groupId > org.springframework.boot </ groupId > < artifactId > spring-boot-starter-web </ artifactId > </ dependency > </ dependencies >

    如果再次运行 mvn dependency:tree ,则会看到现在有很多附加依赖项,包括Tomcat Web 服务器 和Spring Boot本身。

    11.3编写代码

    为了完成我们的应用程序,我们需要创建一个Java文件。 默认情况下,Maven从 src / main / java 编译源代码,因此您需要创建该文件夹结构,然后添加名为 src / main / java / Example.java 的文件以包含以下代码:

    import org.springframework.boot.*;
    import org.springframework.boot.autoconfigure.*;
    import org.springframework.web.bind.annotation.*;
    @RestController
    @EnableAutoConfiguration
    public class Example {
        @RequestMapping("/")
        String home() {
            return "Hello World!";
        public static void main(String[] args) throws Exception {
            SpringApplication.run(Example.class, args);
    

    虽然这里没有太多的代码,但还是有很多重要的事在里头。 我们将在接下来的几节中介绍一些重要的部分。

    11.3.1 @RestController和@RequestMapping注解

    我们的Example类的第一个注解是@RestController。 这被称为stereotype注解。 它为阅读代码的人提供了线索,对于Spring来说,这个类扮演着特定的角色。 在这种情况下,我们的类是一个web @Controller,所以Spring在处理传入的Web请求时会考虑它。

    @RequestMapping注解提供了“路由”信息。 它告诉Spring,任何带有/ path的HTTP请求都应该映射到home方法。@RestController注解告诉Spring将结果字符串直接返回给调用者。

    . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v1.5.9.RELEASE) ....... . . . ....... . . . (log output here) ....... . . . ........ Started Example in 2.222 seconds (JVM running for 6.514)

    如果你打开一个web浏览器到localhost:8080你应该看到下面的输出:

    Hello World!

    要正常退出应用程序点击 ctrl-c

    11.5创建一个可执行的jar

    让我们通过创建一个完全独立的可执行jar文件来完成我们的例子,我们可以在生产环境中运行它。 可执行jar(有时也称为“fat jars”)是包含您编译的类以及您的代码需要运行的所有jar依赖项的归档文件。

    可执行的jar和Java
    Java不提供任何标准的方式来加载嵌套的jar文件(即jar文件本身包含在jar中)。 如果您正在分发自包含的应用程序,这可能会有问题。
    为了解决这个问题,许多开发者使用“超级”罐子。 超级罐子只是将所有罐子里的所有类打包成一个单一的档案。 这种方法的问题在于,很难在应用程序中看到实际使用的库。 如果在多个罐子中使用相同的文件名(但是具有不同的内容),则也可能是有问题的。
    Spring Boot采用了不同的方法,可以直接嵌入jar。

    要创建一个可执行的jar文件,我们需要将 spring-boot-maven-plugin 添加到我们的 pom.xml 。 在依赖关系部分下面插入以下几行:

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
    [INFO] Scanning for projects ... [INFO] [INFO] ------------------------------------------------------------------------ [INFO] Building myproject 0 .0 .1-SNAPSHOT [INFO] ------------------------------------------------------------------------ [INFO] .... .. [INFO] --- maven-jar-plugin :2 .4 :jar ( default-jar ) @ myproject --- [INFO] Building jar: /Users/developer/example/spring-boot-example/target/myproject- 0.0 . 1 -SNAPSHOT.jar [INFO] [INFO] --- spring-boot-maven-plugin: 1.5 . 9 .RELEASE:repackage (default) @ myproject --- [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------

    如果您查看目标目录,则应该看到myproject-0.0.1-SNAPSHOT.jar。 该文件大小应该在10 MB左右。 如果你想查阅里面的内容,你可以使用jar tvf:

    $ jar tvf target/myproject-0.0.1-SNAPSHOT.jar
      .   ____          _            __ _ _
     /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
    ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
     \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
      '  |____| .__|_| |_|_| |_\__, | / / / /
     =========|_|==============|___/=/_/_/_/
     :: Spring Boot ::  (v1.5.9.RELEASE)
    ....... . . .
    ....... . . . (log output here)
    ....... . . .
    ........ Started Example in 2.536 seconds (JVM running for 2.864)

    像以前一样,要优雅地退出应用程序点击 ctrl-c

    12.接下来读什么

    希望本节为您提供了一些Spring Boot的基础知识,并帮助您编写自己的应用程序。 如果您是面向任务的开发人员,则可能需要跳至spring.io,并查看一些入门指南,以解决具体的“如何使用Spring”问题; 我们也有Spring Boot特定的操作指南文档。

    Spring Boot版本库也有一些你可以运行的样本。 样本独立于代码的其余部分(也就是说,您不需要构建其余的代码来运行或使用样本)。

    否则,下一个逻辑步骤是阅读第三部分“使用Spring Boot”。 如果你真的不耐烦,也可以跳过来阅读Spring Boot的特性。

    Part III. 使用Spring Boot

  • Java 1.6作为默认的编译器级别。
  • UTF-8源码编译。
  • 依赖管理部分,允许您省略继承自Spring-Boot-dependencies POM的通用依赖项的标记。明智的资源过滤。
  • 明智的插件配置(( exec plugin , surefire , Git commit ID , shade )。
  • 对application.properties和application.yml进行明智的资源过滤,包括特定于配置文件的文件(例如application-foo.properties和application-foo.yml)
  • < parent > < groupId > org.springframework.boot </ groupId > < artifactId > spring-boot-starter-parent </ artifactId > < version > 1.5.9.RELEASE </ version > </ parent >
    <properties>
        <spring-data-releasetrain.version>Fowler-SR2</spring-data-releasetrain.version>
    </properties>
    < dependency > <!-- Import dependency management from Spring Boot --> < groupId > org.springframework.boot </ groupId > < artifactId > spring-boot-dependencies </ artifactId > < version > 1.5.9.RELEASE </ 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>1.5.9.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    < plugin > < groupId > org.springframework.boot </ groupId > < artifactId > spring-boot-maven-plugin </ artifactId > </ plugin > </ plugins > </ build > dependencies { compile( "org.springframework.boot:spring-boot-starter-web:1.5.9.RELEASE" )

    spring-boot-gradle-plugin也是可用的,并提供了创建可执行的jar和从源代码运行项目的任务。 它还提供依赖性管理,除其他功能外,还允许您省略由Spring Boot管理的任何依赖项的版本号:

    plugins {
        id 'org.springframework.boot' version '1.5.9.RELEASE'
        id 'java'
    repositories {
        jcenter()
    dependencies {
        compile("org.springframework.boot:spring-boot-starter-web")
        testCompile("org.springframework.boot:spring-boot-starter-test")
    

    13.4Ant

    可以使用Apache Ant + Ivy构建Spring Boot项目。 spring-boot-antlib“AntLib”模块也可以帮助Ant创建可执行的jar文件。

    为了声明依赖关系,一个典型的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.5.9.RELEASE" />
        <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-starter Core starter, including auto-configuration support, logging and YAML spring-boot-starter-activemq Starter for JMS messaging using Apache ActiveMQ spring-boot-starter-amqp Starter for using Spring AMQP and Rabbit MQ spring-boot-starter-aop Starter for aspect-oriented programming with Spring AOP and AspectJ spring-boot-starter-artemis Starter for JMS messaging using Apache Artemis spring-boot-starter-batch Starter for using Spring Batch spring-boot-starter-cache Starter for using Spring Framework’s caching support spring-boot-starter-cloud-connectors Starter for using Spring Cloud Connectors which simplifies connecting to services in cloud platforms like Cloud Foundry and Heroku spring-boot-starter-data-cassandra Starter for using Cassandra distributed database and Spring Data Cassandra zebra stripes Starter for using Cassandra distributed database and Spring Data Cassandra spring-boot-starter-data-couchbase Starter for using Couchbase document-oriented database and Spring Data Couchbase spring-boot-starter-data-elasticsearch Starter for using Elasticsearch search and analytics engine and Spring Data Elasticsearch spring-boot-starter-data-gemfire Starter for using GemFire distributed data store and Spring Data GemFire spring-boot-starter-data-jpa Starter for using Spring Data JPA with Hibernate spring-boot-starter-data-ldap Starter for using Spring Data LDAP spring-boot-starter-data-mongodb Starter for using MongoDB document-oriented database and Spring Data MongoDB spring-boot-starter-data-neo4j Starter for using Neo4j graph database and Spring Data Neo4j spring-boot-starter-data-redis Starter for using Redis key-value data store with Spring Data Redis and the Jedis client spring-boot-starter-data-rest Starter for exposing Spring Data repositories over REST using Spring Data REST spring-boot-starter-data-solr Starter for using the Apache Solr search platform with Spring Data Solr spring-boot-starter-freemarker Starter for building MVC web applications using FreeMarker views spring-boot-starter-groovy-templates Starter for building MVC web applications using Groovy Templates views spring-boot-starter-hateoas Starter for building hypermedia-based RESTful web application with Spring MVC and Spring HATEOAS spring-boot-starter-integration Starter for using Spring Integration spring-boot-starter-jdbc Starter for using JDBC with the Tomcat JDBC connection pool spring-boot-starter-jersey Starter for building RESTful web applications using JAX-RS and Jersey. An alternative to spring-boot-starter-web spring-boot-starter-jooq Starter for using jOOQ to access SQL databases. An alternative to spring-boot-starter-data-jpa or spring-boot-starter-jdbc spring-boot-starter-jta-atomikos Starter for JTA transactions using Atomikos spring-boot-starter-jta-bitronix Starter for JTA transactions using Bitronix spring-boot-starter-jta-narayana Spring Boot Narayana JTA Starter spring-boot-starter-mail Starter for using Java Mail and Spring Framework’s email sending support spring-boot-starter-mobile Starter for building web applications using Spring Mobile spring-boot-starter-mustache Starter for building MVC web applications using Mustache views spring-boot-starter-security Starter for using Spring Security spring-boot-starter-social-facebook Starter for using Spring Social Facebook spring-boot-starter-social-linkedin Stater for using Spring Social LinkedIn spring-boot-starter-social-twitter Starter for using Spring Social Twitter spring-boot-starter-test Starter for testing Spring Boot applications with libraries including JUnit, Hamcrest and Mockito spring-boot-starter-thymeleaf Starter for building MVC web applications using Thymeleaf views spring-boot-starter-validation Starter for using Java Bean Validation with Hibernate Validator spring-boot-starter-web Starter for building web, including RESTful, applications using Spring MVC. Uses Tomcat as the default embedded container spring-boot-starter-web-services Starter for using Spring Web Services spring-boot-starter-websocket Starter for building WebSocket applications using Spring Framework’s WebSocket support spring-boot-starter-actuator Starter for using Spring Boot’s Actuator which provides production ready features to help you monitor and manage your application spring-boot-starter-remote-shell Starter for using the CRaSH remote shell to monitor and manage your application over SSH. Deprecated since 1.5 spring-boot-starter-jetty Starter for using Jetty as the embedded servlet container. An alternative to spring-boot-starter-tomcat spring-boot-starter-log4j2 Starter for using Log4j2 for logging. An alternative to spring-boot-starter-logging spring-boot-starter-logging Starter for logging using Logback. Default logging starter spring-boot-starter-tomcat Starter for using Tomcat as the embedded servlet container. Default servlet container starter used by spring-boot-starter-web spring-boot-starter-undertow Starter for using Undertow as the embedded servlet container. An alternative to spring-boot-starter-tomcat import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @EnableAutoConfiguration @ComponentScan public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args);

    15.配置类

    Spring Boot支持基于Java的配置。 虽然可以使用XML源调用SpringApplication.run(),但我们通常建议您的主要来源是@Configuration类。 通常,定义main方法的类也是主要@Configuration的一个好候选。

    import org.springframework.boot.autoconfigure.*;
    import org.springframework.boot.autoconfigure.jdbc.*;
    import org.springframework.context.annotation.*;
    @Configuration
    @EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
    public class MyConfiguration {
    

    如果类不在类路径中,则可以使用注解的excludeName属性,并指定完全限定的名称。 最后,您还可以使用spring.autoconfigure.exclude属性来控制要排除的自动配置类的列表。

    package com.example.service;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    @Service
    public class DatabaseAccountService implements AccountService {
        private final RiskAssessor riskAssessor;
        @Autowired
        public DatabaseAccountService(RiskAssessor riskAssessor) {
            this.riskAssessor = riskAssessor;
        // ...
    

    如果一个bean只有一个构造函数,则可以省略@Autowired,如下例所示:

    @Service
    public class DatabaseAccountService implements AccountService {
        private final RiskAssessor riskAssessor;
        public DatabaseAccountService(RiskAssessor riskAssessor) {
            this.riskAssessor = riskAssessor;
        // ...
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    @SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan
    public class Application {
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
    
    $ java -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=8000,suspend=n \
           -jar target/myapplication-0.0.1-SNAPSHOT.jar

    19.3使用Maven插件

    Spring Boot Maven插件包含一个可用于快速编译和运行应用程序的运行目标。 应用程序以分解形式运行,就像在IDE中一样。

    $ mvn spring-boot:run
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>

    Gradle

    dependencies {
        compile("org.springframework.boot:spring-boot-devtools")
    
    重新启动vs重新加载
    Spring Boot提供的重启技术通过使用两个类加载器来工作。 不改变的类(例如来自第三方jar的类)被加载到基类加载器中。 您正在开发的类将加载到重启类加载器中。 当应用程序重新启动时,重启classloader被丢弃,并创建一个新的。 这种方法意味着应用程序重新启动通常比“冷启动”快得多,因为基类加载器已经可用并且已经被填充了。
    如果您发现重新启动对于您的应用程序来说不够快,或者遇到类加载问题,则可以考虑从ZeroTurnaround中重新加载技术,例如JRebel。 这些工作通过重写类,因为他们被加载,使他们更容易重新加载。

    20.2.1记录条件评估中的变化

    默认情况下,每次重新启动应用程序时,都会记录显示条件评估增量的报告。 该报告显示了对应用程序的自动配置进行的更改,例如添加或删除Bean以及设置配置属性。

    要禁用报告的记录,请设置以下属性:

    spring.devtools.restart.log-condition-evaluation-delta=false
    
    public static void main(String[] args) {
        System.setProperty("spring.devtools.restart.enabled", "false");
        SpringApplication.run(MyApp.class, args);
    

    20.2.5使用触发文件

    如果您在IDE中工作,并尝试连续更改文件,则可能只希望在特定时间触发重新启动。 为此,您可以使用“触发文件”,这是一个特殊的文件,当您想要实际触发重新启动检查时,该文件必须被修改。 只更改文件会触发检查,只有Devtools检测到必须执行某些操作时才会重新启动。 触发器文件可以手动更新或使用IDE插件。

    要使用触发器文件,请将spring.devtools.restart.trigger-file属性设置为触发器文件的路径。

    public static void main(String[] args) {
        SpringApplication.run(MySpringConfiguration.class, args);
    

    当您的应用程序启动时,您应该看到类似于以下输出的内容:

     .   ____          _            __ _ _
     /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
    ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
     \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
      '  |____| .__|_| |_|_| |_\__, | / / / /
     =========|_|==============|___/=/_/_/_/
     :: Spring Boot ::   v2.0.0.BUILD-SNAPSHOT
    2013-07-31 00:08:16.117  INFO 56603 --- [           main] o.s.b.s.app.SampleApplication            : Starting SampleApplication v0.1.0 on mycomputer with PID 56603 (/apps/myapp.jar started by pwebb)
    2013-07-31 00:08:16.166  INFO 56603 --- [           main] ationConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@6e5a8246: startup date [Wed Jul 31 00:08:16 PDT 2013]; root of context hierarchy
    2014-03-04 13:09:54.912  INFO 41370 --- [           main] .t.TomcatServletWebServerFactory : Server initialized with port: 8080
    2014-03-04 13:09:56.501  INFO 41370 --- [           main] o.s.b.s.app.SampleApplication            : Started SampleApplication in 2.992 seconds (JVM running for 3.658)

    默认情况下,会显示INFO日志消息,其中包括一些相关的启动详细信息,例如启动应用程序的用户。

    23.1启动失败

    如果您的应用程序无法启动,已注册的FailureAnalyzers将有机会提供专门的错误消息和具体操作来解决问题。 例如,如果在端口8080上启动Web应用程序,并且该端口已被使用,则应该看到类似于以下消息的内容:

    ***************************
    APPLICATION FAILED TO START
    ***************************
    Description:
    Embedded servlet container failed to start. Port 8080 was already in use.
    Action:
    Identify and stop the process that's listening on port 8080 or configure this application to listen on another port.
    ${application.formatted-version} 您的应用程序的版本号,如MANIFEST.MF中所声明的,并进行格式化以显示(用括号括起来并以v作为前缀)。 例如(v1.0)。 ${spring-boot.version} 您正在使用的Spring Boot版本。 例如2.0.0.BUILD-SNAPSHOT。 ${spring-boot.formatted-version} 您正在使用的Spring Boot版本,格式化为显示(用括号括起来并以v作为前缀)。 例如(v2.0.0.BUILD-SNAPSHOT)。 ${application.title} 在MANIFEST.MF中声明的应用程序的标题。 例如Implementation-Title:MyApp被打印为MyApp。
    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(MySpringConfiguration.class);
        app.setBannerMode(Banner.Mode.OFF);
        app.run(args);
    

    注:有些事件实际上是在创建ApplicationContext之前触发的,因此您不能将这些监听器注册为@Bean。 您可以使用SpringApplication.addListeners(…)或SpringApplicationBuilder.listeners(…)方法注册它们。

    如果您希望自动注册这些侦听器,无论创建应用程序的方式如何,都可以将META-INF / spring.factories文件添加到您的项目中,并使用org.springframework.context引用您的侦听器。 ApplicationListener键,如以下示例所示:

    org.springframework.context.ApplicationListener= com.example.project.MyListener

  • ApplicationStartingEvent在运行开始时发送,除了注册监听器和初始化器之外的任何处理之前。
  • 当在上下文中使用的环境是已知的但在创建上下文之前发送ApplicationEnvironmentPreparedEvent。
  • ApplicationPreparedEvent在刷新开始之前,但在bean定义加载之后发送。
  • 在刷新之后发送ApplicationReadyEvent并处理任何相关的回调,以指示应用程序已准备好为请求提供服务。
  • 如果启动时出现异常,则发送ApplicationFailedEvent。
  • import org.springframework.boot.*
    import org.springframework.beans.factory.annotation.*
    import org.springframework.stereotype.*
    @Component
    public class MyBean {
        @Autowired
        public MyBean(ApplicationArguments args) {
            boolean debug = args.containsOption("debug");
            List<String> files = args.getNonOptionArgs();
            // if run with "--debug logfile.txt" debug=true, files=["logfile.txt"]
    public class MyBean implements CommandLineRunner {
        public void run(String... args) {
            // Do something...
    

    您还可以实现org.springframework.core.Ordered接口或使用org.springframework.core.annotation.Order注释,如果定义了多个CommandLineRunner或ApplicationRunner bean,则必须按特定顺序调用它们。

    23.9应用退出

    每个SpringApplication都会向JVM注册一个关闭钩子,以确保ApplicationContext在退出时正常关闭。 所有标准的Spring生命周期回调(比如DisposableBean接口或者@PreDestroy注解)都可以使用。

    另外,如果在调用SpringApplication.exit()时想要返回特定的退出代码,bean可以实现org.springframework.boot.ExitCodeGenerator接口。 然后可以将此退出代码传递给System.exit()以将其作为状态代码返回,如以下示例所示:

    @SpringBootApplication
    public class ExitCodeApplication {
        @Bean
        public ExitCodeGenerator exitCodeGenerator() {
            return () -> 42;
        public static void main(String[] args) {
            System.exit(SpringApplication
                    .exit(SpringApplication.run(ExitCodeApplication.class, args)));
    

    另外,ExitCodeGenerator接口可能由异常实现。 遇到这样的异常时,Spring Boot会返回实现的getExitCode()方法提供的退出代码。

    23.10管理员功能

    通过指定spring.application.admin.enabled属性,可以为应用程序启用与管理相关的功能。 这暴露了平台MBeanServer上的SpringApplicationAdminMXBean。 您可以使用此功能远程管理您的Spring Boot应用程序。 此功能对于任何服务包装器实现也可能是有用的。

  • 在主目录上开发Devtools全局设置属性(当devtools处于活动状态时〜/ .spring-boot-devtools.properties)。
  • 在你的测试中使用@TestPropertySource注解。
  • 在你的测试中@ SpringBootTest#属性注解属性。
  • 命令行参数。
  • 来自SPRING_APPLICATION_JSON的属性(嵌入在环境变量或系统属性中的内联JSON)。
  • ServletConfig初始化参数。
  • ServletContext初始化参数。
  • 来自java:comp / env的JNDI属性。
  • Java系统属性(System.getProperties())。
  • OS环境变量。
  • 一个RandomValuePropertySource只具有随机的属性*。
  • 打包jar(application- {profile} .properties和YAML变体)之外的特定于配置文件的应用程序属性。
  • 打包在您的jar(application- {profile} .properties和YAML变体)中的特定于配置文件的应用程序属性。
  • 应用程序属性在打包的jar之外(application.properties和YAML变体)。
  • 打包在jar中的应用程序属性(application.properties和YAML变体)。
  • @Configuration类的@PropertySource注释。
  • 默认属性(使用SpringApplication.setDefaultProperties指定)。
  • import org.springframework.stereotype.*
    import org.springframework.beans.factory.annotation.*
    @Component
    public class MyBean {
        @Value("${name}")
        private String name;
        // ...
    

    在您的应用程序类路径中(例如,在您的jar中),您可以拥有一个application.properties文件,该文件为名称提供了一个合理的默认属性值。 在新环境中运行时,可以在jar外部提供一个application.properties文件来覆盖该名称。 对于一次性测试,您可以使用特定的命令行开关(例如,java -jar app.jar –name =“Spring”)启动。

    提示:可以使用环境变量在命令行上提供SPRING_APPLICATION_JSON属性。 例如,您可以在UN * X shell中使用以下行:

    $ SPRING_APPLICATION_JSON =’{“acme”:{“name”:“test”}}’java -jar myapp.jar
    在前面的例子中,Spring结束了acme.name = test。 您也可以在System属性中将spring提供为spring.application.json,如下例所示:

    $ java -Dspring.application.json =’{“name”:“test”}’-jar myapp.jar
    您还可以使用命令行参数提供JSON,如以下示例所示:

    $ java -jar myapp.jar –spring.application.json =’{“name”:“test”}’
    您还可以将JSON作为JNDI变量提供,如下所示:java:comp / env / spring.application.json。

    my.bignumber=${random.long} my.uuid=${random.uuid} my.number.less.than.ten=${random.int(10)} my.number.in.range=${random.int[1024,65536]}

    ndom.int *语法是OPEN值(,max)CLOSE其中OPEN,CLOSE是任何字符和值,max是整数。 如果提供最大值,则值是最小值,最大值是最大值(不包括)。

    24.2访问命令行属性

    默认情况下,SpringApplication将任何命令行选项参数(即以“ - ”开头的参数,例如–server.port = 9000)转换为属性并将其添加到Spring环境。 如前所述,命令行属性总是优先于其他属性源。

    如果您不希望将命令行属性添加到环境中,则可以使用SpringApplication.setAddCommandLineProperties(false)将其禁用。

    24.3应用程序属性文件

    SpringApplication从以下位置的application.properties文件加载属性,并将它们添加到Spring环境中:

    environments.dev.url=http://dev.example.com
    environments.dev.name=Developer Setup
    environments.prod.url=http://another.example.com
    environments.prod.name=My Cool App

    YAML列表被表示为带有[index]解引用的属性键。 例如,考虑下面的YAML:

    servers: - dev.example.com - another.example.com

    前面的例子将被转换成这些属性:

    my.servers[0]=dev.example.com
    my.servers[1]=another.example.com

    要通过使用Spring DataBinder实用程序(这是@ConfigurationProperties所做的)绑定到这样的属性,您需要在java.util.List(或Set)类型的目标Bean中拥有一个属性,并且您需要提供一个setter 或者用一个可变的值初始化它。 例如,以下示例绑定到以前显示的属性:

    @ConfigurationProperties(prefix="my")
    public class Config {
        private List<String> servers = new ArrayList<String>();
        public List<String> getServers() {
            return this.servers;
    import java.util.List;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    @ConfigurationProperties("acme")
    public class AcmeProperties {
        private boolean enabled;
        private InetAddress remoteAddress;
        private final Security security = new Security();
        public boolean isEnabled() { ... }
        public void setEnabled(boolean enabled) { ... }
        public InetAddress getRemoteAddress() { ... }
        public void setRemoteAddress(InetAddress remoteAddress) { ... }
        public Security getSecurity() { ... }
        public static class Security {
            private String username;
            private String password;
            private List<String> roles = new ArrayList<>(Collections.singleton("USER"));
            public String getUsername() { ... }
            public void setUsername(String username) { ... }
            public String getPassword() { ... }
            public void setPassword(String password) { ... }
            public List<String> getRoles() { ... }
            public void setRoles(List<String> roles) { ... }
    

    前面的POJO定义了以下属性:

  • acme.enabled,默认为false。
  • acme.remote-address,可以从String强制类型。
  • acme.security.username,带有嵌套的“安全”对象,其名称由属性的名称确定。 特别是,返回类型没有在那里使用,可能是SecurityProperties。
  • acme.security.password。
  • acme.security.roles,带有一个String的集合。
  • 注:getters和setter通常是强制的,因为绑定是通过标准的Java Beans属性描述符来完成的,就像在Spring MVC中一样。在以下情况下,可能会忽略setter:

    地图,只要它们被初始化,需要一个getter,但不一定是一个setter,因为它们可以被绑定器改变。
    集合和数组可以通过索引(通常使用YAML)或使用单个逗号分隔值(属性)来访问。在后一种情况下,二传手是强制性的。我们建议始终为这种类型添加一个setter。如果初始化一个集合,确保它不是不可变的(如前面的例子)。
    如果嵌套的POJO属性被初始化(如上例中的Security域),则不需要setter。如果您希望活页夹使用其默认构造函数即时创建实例,则需要一个setter。
    有些人使用Project Lombok来自动添加getter和setter。确保Lombok不会为这种类型生成任何特定的构造函数,因为它被容器自动使用来实例化对象。

    @Configuration
    @EnableConfigurationProperties(AcmeProperties.class)
    public class MyConfiguration {