Spring Boot 官方文档摘要

Spring Boot 官方文档摘要

一、Develop Your First Spring Boot Application

Spring Boot 依赖于 groupIdorg.springframework.boot 的组件。一般来说都是依赖 spring-boot-starter-parent 组件,也可以根据需要添加更多的 Starter

以下是pom文件的配置:

<?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.1.0.M3</version>
    </parent>
    
    <!-- Add dependencies -->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-properties-migrator</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
        	<groupId>org.springframework.boot</groupId>
        	<artifactId>spring-boot-starter-web</artifactId>
    	</dependency>
    </dependencies>
    
    <!-- (you don't need this if you are using a .RELEASE version) -->
    <repositories>
        <repository>
            <id>spring-snapshots</id>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots><enabled>true</enabled></snapshots>
        </repository>
        <repository>
            <id>spring-milestones</id>
            <url>https://repo.spring.io/milestone</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-snapshots</id>
            <url>https://repo.spring.io/snapshot</url>
        </pluginRepository>
        <pluginRepository>
            <id>spring-milestones</id>
            <url>https://repo.spring.io/milestone</url>
        </pluginRepository>
    </pluginRepositories>
<project/>

mvn denpendency:tree会打印并以树形展示项目依赖

1. Maven

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

  • Java 1.6作为默认的编译级别。
  • UTF-8源码编码。
  • 依赖管理部分,对于常用的依赖允许你忽略``标签,从spring-boot-dependencies继承POM。
  • 合理的资源过滤。
  • 合理的插件配置(exec plugin, surefire, Git commit ID, shade)。
  • 对包括特定配置文件的application.propertiesapplication.yml的合理资源过滤(例如,application-foo.propertiesapplication-foo.yml)。

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

2. 使用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中的定义的设置。

3. Starters

通过Starters你可以获得相关技术的一站式服务所有官方的启动器都有一个类似的命名模式:spring-boot-starter-*,*是应用特性类型, 下面的应用启动器由Spring Boot提供,在org.springframework.boot组下:

Spring Boot 应用启动器

NameDescription
spring-boot-starter-thymeleafStarter for building MVC web applications using Thymeleaf views
spring-boot-starter-data-couchbaseStarter for using Couchbase document-oriented database and Spring Data Couchbase
spring-boot-starter-artemisStarter for JMS messaging using Apache Artemis
spring-boot-starter-web-servicesStarter for using Spring Web Services
spring-boot-starter-mailStarter for using Java Mail and Spring Framework’s email sending support
spring-boot-starter-data-redisStarter for using Redis key-value data store with Spring Data Redis and the Jedis client
spring-boot-starter-webStarter for building web, including RESTful, applications using Spring MVC. Uses Tomcat as the default embedded container
spring-boot-starter-data-gemfireStarter for using GemFire distributed data store and Spring Data GemFire
spring-boot-starter-activemqStarter for JMS messaging using Apache ActiveMQ
spring-boot-starter-data-elasticsearchStarter for using Elasticsearch search and analytics engine and Spring Data Elasticsearch
spring-boot-starter-integrationStarter for using Spring Integration
spring-boot-starter-testStarter for testing Spring Boot applications with libraries including JUnit, Hamcrest and Mockito
spring-boot-starter-jdbcStarter for using JDBC with the Tomcat JDBC connection pool
spring-boot-starter-mobileStarter for building web applications using Spring Mobile
spring-boot-starter-validationStarter for using Java Bean Validation with Hibernate Validator
spring-boot-starter-hateoasStarter for building hypermedia-based RESTful web application with Spring MVC and Spring HATEOAS
spring-boot-starter-jerseyStarter for building RESTful web applications using JAX-RS and Jersey. An alternative to spring-boot-starter-web
spring-boot-starter-data-neo4jStarter for using Neo4j graph database and Spring Data Neo4j
spring-boot-starter-websocketStarter for building WebSocket applications using Spring Framework’s WebSocket support
spring-boot-starter-aopStarter for aspect-oriented programming with Spring AOP and AspectJ
spring-boot-starter-amqpStarter for using Spring AMQP and Rabbit MQ
spring-boot-starter-data-cassandraStarter for using Cassandra distributed database and Spring Data Cassandra
spring-boot-starter-social-facebookStarter for using Spring Social Facebook
spring-boot-starter-jta-atomikosStarter for JTA transactions using Atomikos
spring-boot-starter-securityStarter for using Spring Security
spring-boot-starter-mustacheStarter for building MVC web applications using Mustache views
spring-boot-starter-data-jpaStarter for using Spring Data JPA with Hibernate
spring-boot-starterCore starter, including auto-configuration support, logging and YAML
spring-boot-starter-groovy-templatesStarter for building MVC web applications using Groovy Templates views
spring-boot-starter-freemarkerStarter for building MVC web applications using FreeMarker views
spring-boot-starter-batchStarter for using Spring Batch
spring-boot-starter-social-linkedinStater for using Spring Social LinkedIn
spring-boot-starter-cacheStarter for using Spring Framework’s caching support
spring-boot-starter-data-solrStarter for using the Apache Solr search platform with Spring Data Solr
spring-boot-starter-data-mongodbStarter for using MongoDB document-oriented database and Spring Data MongoDB
spring-boot-starter-jooqStarter for using jOOQ to access SQL databases. An alternative to spring-boot-starter-data-jpa or spring-boot-starter-jdbc
spring-boot-starter-jta-narayanaSpring Boot Narayana JTA Starter
spring-boot-starter-cloud-connectorsStarter for using Spring Cloud Connectors which simplifies connecting to services in cloud platforms like Cloud Foundry and Heroku
spring-boot-starter-jta-bitronixStarter for JTA transactions using Bitronix
spring-boot-starter-social-twitterStarter for using Spring Social Twitter
spring-boot-starter-data-restStarter for exposing Spring Data repositories over REST using Spring Data REST

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

Spring Boot 产品启动器

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

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

Spring Boot 技术启动器

NameDescription
spring-boot-starter-undertowStarter for using Undertow as the embedded servlet container. An alternative to spring-boot-starter-tomcat
spring-boot-starter-jettyStarter for using Jetty as the embedded servlet container. An alternative to spring-boot-starter-tomcat
spring-boot-starter-loggingStarter for logging using Logback. Default logging starter
spring-boot-starter-tomcatStarter for using Tomcat as the embedded servlet container. Default servlet container starter used by spring-boot-starter-web
spring-boot-starter-log4j2Starter for using Log4j2 for logging. An alternative to spring-boot-starter-logging
4. 使用“default”包

当一个类没有包含一个package声明时,它当做是在default package中。通常情况下不建议使用default package,应该避免使用它。当Spring Boot应用使用@ComponentScan@EntityScan@SpringBootApplication它会引起一些特别的问题,因为Spring Boot会读取每个jar中的每个类。

Java推荐的包命名规范,使用一个反转的域名(例如,com.example.project)。

5. 主应用类的定义

通常主应用类是放在其他类之上的根包中,这里展示一个典型的布局:

com
 +- example
     +- myproject
         +- Application.java
         |
         +- domain
         |   +- Customer.java
         |   +- CustomerRepository.java
         |
         +- service
         |   +- CustomerService.java
         |
         +- web
             +- CustomerController.java

其中Application.java即是主类,@EnableAutoConfiguration注解经常放在你的主类(main class)中,对于某些像它隐式的定义了一个基search package,例如,如果你正在写一个JPA应用,@EnableAutoConfiguration注解的类所在的包将被用来搜索@Entity项。根包的应用也允许使用@ComponentScan注解而不需要指定basePackage特性。如果你的主类是在根包中,你也可以使用@SpringBootApplication注解。

Application.java文件会声明main方法和基本的@Configuration

package com.example.myproject;

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);
    }

}

可以直接使用SpringBootApplication代替这三个注解(其实是两个,@ComponentScan会自动获取所有Spring组件,包括@Configuration

同时,不必将所有的@Configuration放入一个单独的类,可以通过@Import导入额外的配置类,当然正如上文所说, @ComponentScan来自动获得

如果绝对的必须使用基于XML的配置,推荐仍然从@Configuration类开始,使用额外的@ImportResource注解来加载XML配置文件。

@EnableAutoConfiguration@SpringBootApplication注解 会自动的将已经添加在Spring的依赖配置成bean, 如果你发现正在应用特定的你不想使用的自动配置类,你可以使用@EnableAutoConfiguration注解的exclude特性来禁用它们。 如:

@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
6. 开发工具

pring Boot包含额外的工具集合,可以使应用开发的过程更方便一点。spring-boot-devtools模块可以包含进任何工程,用来提供额外的程序调试特性。为了添加工具支持,简单的添加模块依赖到你的构建系统中:

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

自动重启

classpath中的文件修改时,使用spring-boot-devtools的应用会自动重启。当使用IDE开发时,这是一个很有用的功能,因为代码改变时它能快速的进行反馈。默认情况下,会监控classpath指向的文件夹中任何条目的变化。注意某些资源例如静态资源和视图模板不需要重启应用。

DevTools依赖应用上下文关闭钩子来进行重启期间的关闭。如果你禁用了关闭钩子它将不能正确工作(SpringApplication.setRegisterShutdownHook(false))。

当决定classpath中输入引起的改变是否应该触发重启时,DevTools会自动忽略命名为spring-bootspring-boot-devtoolsspring-boot-autoconfigurespring-boot-actuatorspring-boot-starter的工程。

某些资源当它们改变时不一定需要触发重启。默认情况下,/META-INF/maven/META-INF/resources/resources/static/public/templates中资源的改变不会触发重启,但会触发实时重载。如果你想定制这些例外项,你可以使用spring.devtools.restart.exclude属性。例如,仅排除/static/public,设置如下:

spring.devtools.restart.exclude=static/**,public/**

如果你想使用重启功能你可以通过spring.devtools.restart.enabled属性禁用它。

public static void main(String[] args) {
    System.setProperty("spring.devtools.restart.enabled", "false");
    SpringApplication.run(MyApp.class, args);
}

实时重载

spring-boot-devtools模块包含一个内嵌的实时重载服务器,当资源改变时可以用来触发浏览器重新刷新。 当你的应用运行时,如果你不想启动实时重载服务器,你可以将spring.devtools.livereload.enabled属性设为false

一次你只可以运行一个实时重载服务器。在启动你的应用之前,确保没有其它的实时重载服务器在运行。如果你从你的IDE中启动多个应用,只有第一个应用有实时重载服务器支持。

二、Spring Boot 特性
1. 应用事件和监听器

除了平常的Spring框架事件之外,例如ContextRefreshedEventSpringApplication会发送一些其它的应用事件。

ApplicationContext创建之前实际上会触发一些事件,因此你不能使用@Bean来注册这些监听器。你可以通过SpringApplication.addListeners(…)SpringApplicationBuilder.listeners(…)方法来注册这些监听器。

如果你想自动注册这些监听器,不管上下文的创建方式,你可以在你的工程中添加META-INF/spring.factories文件,并通过org.springframework.context.ApplicationListener作为key来引用你的监听器。

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

当你的应用运行时,应用事件以下面的顺序发送:

  1. 在运行启动时发送ApplicationStartedEvent,除了监听器和初始化器注册之外,在进行任何处理之前发送。
  2. 当在上下文中使用的Environment已知时,发送ApplicationEnvironmentPreparedEvent,但发送是在上下文创建之前。
  3. 在再刷新启动之前,但在bean定义加载之后,发送ApplicationPreparedEvent
  4. 在再刷新之后,发送ApplicationReadyEvent,任何相关的回调函数都处理完成之后,意味着应用已经准备处理服务请求了。
  5. 如果启动时出现异常,发送ApplicationFailedEvent.
2. Web环境

SpringApplication会尝试创建代表你的合适的ApplicationContext类型。默认情况下,会使用AnnotationConfigApplicationContextAnnotationConfigEmbeddedWebApplicationContext,依赖于你是否在开发一个web应用。

使用的决定web environment的算法是相对简单的(基于现有的一些类)。如果你需要覆写默认值你可以使用setWebEnvironment(boolean webEnvironment)

当在JUnit测试时使用SpringApplication,经常需要调用setWebEnvironment(false)

3. 使用ApplicationRunner或CommandLineRunner

如果你需要在SpringApplication启动时运行一些特定的代码,你可以实现ApplicationRunnerCommandLineRunner接口。这两个接口以同样方式工作,并有一个单独的run方法,在SpringApplication.run(…)之前会调用这个run方法。

CommandLineRunner接口提供了对应用参数的访问,应用参数作为一个简单的字符串数组,而ApplicationRunner使用前面描述的ApplicationArguments接口。

import org.springframework.boot.*
import org.springframework.stereotype.*

@Component
public class MyBean implements CommandLineRunner {

    public void run(String... args) {
        // Do something...
    }

}

另外,如果定义的CommandLineRunnerApplicationRunner beans必须以指定顺序调用,你可以实现org.springframework.core.Ordered接口或org.springframework.core.annotation.Order 注解。

4. 应用退出

为了确保ApplicationContext在关闭时安全退出, 每个SpringApplication都会在JVM中注册一个关闭钩子。所有的标准Spring生命周期回调函数(例如DisposableBean接口,或@PreDestroy注解)都会被使用。

另外,当应用退出时,如果它们想返回一个特定的退出码,beans可以实现org.springframework.boot.ExitCodeGenerator接口。

5. 外部配置

Spring Boot允许你进行外部化配置,因此可以将同样的应用代码在不同的环境中运行。你可以使用属性文件,YAML文件,环境变量和命令行参数来进行外部化配置。

5.1 配置随机值

当注入随机值时,RandomValuePropertySource是很有用的(例如,注入秘密或测试用例)。它可以产生integerslongsuuidsstrings,例如:

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

5.2 应用属性文件

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

  1. 当前目录的子目录/config
  2. 当前目录
  3. classpath中的/config
  4. classpath的根目录

这个列表是按优先级排序的(在更高位置的属性会重写定义在更低位置的属性)。

你也可以使用YAML(.yml)文件来代替.properties文件。

5.3 属性中的占位符

当使用application.properties中的值时,会通过现有的Environment进行过滤,因此你可以参考前面定义的值(例如从系统属性中)。

app.name=MyApp
app.description=${app.name} is a Spring Boot application

5.4 使用YAML代替Properties

YAML是JSON的超集,它可以用一种非常方便的形式来指定分层配置数据。当你的类路径有SnakeYAML库时,SpringApplication类自动支持YAML作为properties的一个替代品。

如果你使用‘Starters’,SnakeYAML将由spring-boot-starter自动提供。

加载YAML

Spring框架提供了两个类用来方便的加载YAML文档。YamlPropertiesFactoryBean将加载YAML作为PropertiesYamlMapFactoryBean将加载YAML作为Map

例如,下面的YAML文档:

environments:
    dev:
        url: http://dev.bar.com
        name: Developer Setup
    prod:
        url: http://foo.bar.com
        name: My Cool App

将被转换成这些属性:

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

YAML列表通过[index]解引用表示为属性的key,例如这个YAML:

my:
   servers:
       - dev.bar.com
       - foo.bar.com

将被转换成这些属性:

my.servers[0]=dev.bar.com
my.servers[1]=foo.bar.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;
    }
}

6. Profiles

Spring Profiles提供了一种隔离部分应用配置的方式,并让这些配置只在特定的环境生效。任何带有@Profile标记的@Component@Configuration在加载时都会受限制:

@Configuration
@Profile("production")
public class ProductionConfiguration {

    // ...

}

以正常的Spring方式,你可以使用spring.profiles.active Environment属性来指定激活哪一个profiles。你可以在任何常见的方式指定这个属性,例如你可以在你的application.properties中包含它:

spring.profiles.active=dev,hsqldb

或在命令行用--spring.profiles.active=dev,hsqldb指定。

7. Logging

默认情况下,如果使用Starters,Logback将作为日志。也要包含恰当的Logback规则来保证依赖库使用Java Util Logging,Commons Logging,Log4J或SLF4J都能正确工作。

在Java中有许多日志框架可用。不必担心上面的列表看起来有点混乱。通常情况下你不需要改变你的日志依赖,Spring Boot默认情况下能很好的工作。

日志级别

Spring支持的所有日志系统都可以在Spring的Environment中设置日志级别(例如在application.properties设置),使用logging.level.*=LEVEL进行设置,LEVEL是TRACE,DEBUG,INFO,WARN,ERROR,FATAL,OFF中的一个。root日志器可以用logging.level.root来配置。例如在application.properties中:

logging.level.root=WARN
logging.level.org.springframework.web=DEBUG
logging.level.org.hibernate=ERROR

默认情况下Spring Boot重新映射Thymeleaf的INFO信息,为了它们能在DEBUG级别进行输出。这能帮助减少标准日志输出中的噪声。关于怎样在你自己的配置中使用重新映射的更多细节请看LevelRemappingAppender

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值