Spring-2.0.0.M3超详细文档(第一弹)

内容很长建议收藏后食用.这只是第一波文档,后续会更上,关注,在看走一波

spring for start

@RestController and @RequestMapping 注解

@RestController 是一个构造性注解,它为阅读者提供了标注,对于 Spring 来说这个类扮演者特殊的角色.
@RequestMapping 标注这是一个’路由’,它会告诉 Spring 任何 HTTP 请求都需要印射到不同的’路由’上,@RestController 注解告诉 Spring 对于调用方的返回结果是字符串的

@RestController and @RequestMapping 并不是 Spring Boot 独有的,详细可以参考 Spring 中的
MVC section部分

@EnableAutoConfiguration 注解

第二类级别的注解就是 @EnableAutoConfiguration,这个注释告诉 Spring Boot 根据添加的 jar 依赖关系“猜测”您将如何配置 Spring spring-boot-starter-web 计入了 Tomcat 和 Spring MVC,自动配置默认认为你在开发一个 Spring 的 web 项目

main 方法

应用的最后一个部分就是main方法,这只是一个遵循 Java 约定程序入口点的标准方法,SpringApplication 由 mian 方法中的 run 代理,SpringApplication 就会引导我们的应用,启动 Spring 会反向自动配置 Tomcat web 服务.我们需要类的 run 方法来告诉 SpringApplication 谁才是 Spring 的主要组件.args 数组也可以传入任意的命令行参数.

可执行的 jar

通常我们会把所有的依赖 jar 打入一个 jar 之中,但是可能会出现相同 jar 包名,但是内容不相同的问题,Spring 采用了多种方式,允许在实际中直接嵌套 jar.

创建一个可执行的 jar 需要在 pom.xml 文件中引入spring-boot-maven-plugin,如果你未使用spring-boot-starter-parent,你需要重新配置,可以参考plugin
文档

你可以使用mvn package 进行打包.之后你会在target目录下看见项目名称-0.0.1-SNAPSHOT.jar,如果你想查看 jar 内部内容,可以使用jar tvf,你可以看见更小的文件***-0.0.1-SNAPSHOT.jar.originaltarget目录下,这个文件就是 Maven 在 Spring Boot 重新打包之前创建的原始 jar 文件

使用 Spring Boot

依赖管理

SPring Boot 每个版本都提供了精致的依赖,你不需要在构建配置中为这些依赖提供任何版本,因为 Spring Boot 会为你管理版本,当你升级 Spring Boot 这些依赖会一起升级.

如果你觉得有必要的话,你也可以强行覆盖这个版本依赖

Spring Boot 的依赖包含了所有 spring 模块和完善的一些三方库.

每个Spring Boot版本都与Spring Framework 的基本版本有关联,所以强烈建议不要自行指定其版本

Maven

Maven 用户可以从spring-boots-starter-parent中获得默认配置,它会提供如下功能

  • Java 1.8 是默认的编译器级别
  • UTF-8 是默认的编码
  • 允许你忽略从 spring-boot-dependencies 继承来的依赖的<version>标签
  • 智能的资源过滤
  • 智能的插件配置 (shade,surefire …)
  • application.propertiesapplication.yml智能过滤资源或者其他的一些文件(application-foo.propertiesapplication.properties.yml)

最后一点:由于默认的配置文件支持 Spring 样式的占位符${..},所以 Maven 的过滤器使用@..@占位符.(你也可以使用 Maven 的 resource.delimilter 覆盖它)

继承启动类父类依赖 pom 使用 Spring Boot

只需要将spring-boot-starter-parent设置为 pom 中的父类依赖

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

必须指定Spring Boot启动器版本,除非你已经引入其它版本的启动器

这是 spring-boot-dependencies的 pom

无需依赖启动类父类依赖来使用 Spring Boot

如果你不想使用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.M3</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

使用 spring-boot-maven-plugin

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,你无需配置此插件,除非你想覆盖它的一些设置

Starter (入门程序)

入门程序包含了许多快速使用并且启动的依赖项.并且各自有一组支持传递依赖的依赖

所有的官方入门程序都遵循 spring-boot-starter-*的命名方式

以下是 Spring 官方提供的 Starter

NameDescriptionPom

spring-boot-starter

Core starter, including auto-configuration support, logging and YAML

Pom

spring-boot-starter-activemq

Starter for JMS messaging using Apache ActiveMQ

Pom

spring-boot-starter-amqp

Starter for using Spring AMQP and Rabbit MQ

Pom

spring-boot-starter-aop

Starter for aspect-oriented programming with Spring AOP and AspectJ

Pom

spring-boot-starter-artemis

Starter for JMS messaging using Apache Artemis

Pom

spring-boot-starter-batch

Starter for using Spring Batch

Pom

spring-boot-starter-cache

Starter for using Spring Framework’s caching support

Pom

spring-boot-starter-cloud-connectors

Starter for using Spring Cloud Connectors which simplifies connecting to services in cloud platforms like Cloud Foundry and Heroku

Pom

spring-boot-starter-data-cassandra

Starter for using Cassandra distributed database and Spring Data Cassandra

Pom

spring-boot-starter-data-cassandra-reactive

Starter for using Cassandra distributed database and Spring Data Cassandra Reactive

Pom

spring-boot-starter-data-couchbase

Starter for using Couchbase document-oriented database and Spring Data Couchbase

Pom

spring-boot-starter-data-elasticsearch

Starter for using Elasticsearch search and analytics engine and Spring Data Elasticsearch

Pom

spring-boot-starter-data-jpa

Starter for using Spring Data JPA with Hibernate

Pom

spring-boot-starter-data-ldap

Starter for using Spring Data LDAP

Pom

spring-boot-starter-data-mongodb

Starter for using MongoDB document-oriented database and Spring Data MongoDB

Pom

spring-boot-starter-data-mongodb-reactive

Starter for using MongoDB document-oriented database and Spring Data MongoDB Reactive

Pom

spring-boot-starter-data-neo4j

Starter for using Neo4j graph database and Spring Data Neo4j

Pom

spring-boot-starter-data-redis

Starter for using Redis key-value data store with Spring Data Redis and the Jedis client

Pom

spring-boot-starter-data-redis-reactive

Starter for using Redis key-value data store with Spring Data Redis reactive and the Lettuce client

Pom

spring-boot-starter-data-rest

Starter for exposing Spring Data repositories over REST using Spring Data REST

Pom

spring-boot-starter-data-solr

Starter for using the Apache Solr search platform with Spring Data Solr

Pom

spring-boot-starter-freemarker

Starter for building MVC web applications using FreeMarker views

Pom

spring-boot-starter-groovy-templates

Starter for building MVC web applications using Groovy Templates views

Pom

spring-boot-starter-hateoas

Starter for building hypermedia-based RESTful web application with Spring MVC and Spring HATEOAS

Pom

spring-boot-starter-integration

Starter for using Spring Integration

Pom

spring-boot-starter-jdbc

Starter for using JDBC with the Tomcat JDBC connection pool

Pom

spring-boot-starter-jersey

Starter for building RESTful web applications using JAX-RS and Jersey. An alternative to spring-boot-starter-web

Pom

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

Pom

spring-boot-starter-jta-atomikos

Starter for JTA transactions using Atomikos

Pom

spring-boot-starter-jta-bitronix

Starter for JTA transactions using Bitronix

Pom

spring-boot-starter-jta-narayana

Spring Boot Narayana JTA Starter

Pom

spring-boot-starter-mail

Starter for using Java Mail and Spring Framework’s email sending support

Pom

spring-boot-starter-mobile

Starter for building web applications using Spring Mobile

Pom

spring-boot-starter-mustache

Starter for building web applications using Mustache views

Pom

spring-boot-starter-quartz

Spring Boot Quartz Starter

Pom

spring-boot-starter-security

Starter for using Spring Security

Pom

spring-boot-starter-social-facebook

Starter for using Spring Social Facebook

Pom

spring-boot-starter-social-linkedin

Stater for using Spring Social LinkedIn

Pom

spring-boot-starter-social-twitter

Starter for using Spring Social Twitter

Pom

spring-boot-starter-test

Starter for testing Spring Boot applications with libraries including JUnit, Hamcrest and Mockito

Pom

spring-boot-starter-thymeleaf

Starter for building MVC web applications using Thymeleaf views

Pom

spring-boot-starter-validation

Starter for using Java Bean Validation with Hibernate Validator

Pom

spring-boot-starter-web

Starter for building web, including RESTful, applications using Spring MVC. Uses Tomcat as the default embedded container

Pom

spring-boot-starter-web-services

Starter for using Spring Web Services

Pom

spring-boot-starter-webflux

Starter for building WebFlux applications using Spring Framework’s Reactive Web support

Pom

spring-boot-starter-websocket

Starter for building WebSocket applications using Spring Framework’s WebSocket support

Pom

除了这些入门程序,Spring同样也提供一些准备生产的版本

NameDescriptionPom

spring-boot-starter-actuator

Starter for using Spring Boot’s Actuator which provides production ready features to help you monitor and manage your application

Pom

Spring 也提供了一些启动器

NameDescriptionPom

spring-boot-starter-jetty

Starter for using Jetty as the embedded servlet container. An alternative to spring-boot-starter-tomcat

Pom

spring-boot-starter-json

Starter for reading and writing json

Pom

spring-boot-starter-log4j2

Starter for using Log4j2 for logging. An alternative to spring-boot-starter-logging

Pom

spring-boot-starter-logging

Starter for logging using Logback. Default logging starter

Pom

spring-boot-starter-reactor-netty

Starter for using Reactor Netty as the embedded reactive HTTP server.

Pom

spring-boot-starter-tomcat

Starter for using Tomcat as the embedded servlet container. Default servlet container starter used by spring-boot-starter-web

Pom

spring-boot-starter-undertow

Starter for using Undertow as the embedded servlet container. An alternative to spring-boot-starter-tomcat

Pom

更多spring-boot-starter模块文档,可以参考README file

结构化代码

spring Boot不需要任何结构化代码就可以直接使用.

使用 ‘default’ 包

当一个程序不包含一个package时,它会被默认为是在default package中,通常不鼓励使用default package.对于@ComponentScan,@EntityScan,@SpringBootApplication注解的Spring Boot应用,会导致特定的问题,因为每个jar都会被读取

建议遵循Java的程序包命名约定(反向域名.例如:com.example.project)

查找应用入口

通常建议主程序应用入口(启动类)放在项目根目录下.@EnableAutoConfiguration通常放在主类上,它隐式定义了一些项目的search package

在根目录下使用@ComponentScna注解,无需指定basePackage属性.如果在主类在根目录下,也可以使用@SpringApplication注解

以下是一个经典布局

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

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

}

配置类

Spring Boot 支持基于java的配置.尽管SpringApplication可以和XML一起使用,但是通常建议主要来源使用单个的@Configuration类.通常定义main方法的类也是主要的@Configuration

网上有很多使用XML配置Spring的实例.但是如果有可能,尽量尝试使用等效的基于Java的配置. 搜索Enable.* 可能会是一个好的起点

导入其他配置类

无需将所有的@Configuration放在一个类中.@Import注解可用于导入其他配置类.你也可以使用@ComponentScan自动拾取Spring组件,其中包括了@Configuration类.

导入XML配置

如果要使用XML配置,我们建议仍从@Configuration类开始.然后,可以使用@ImportResource注解来加载XML配置文件.

自动配置

Spring Boot 自动配置会尝试根据添加的jar依赖项自动配置Spring应用.

你需要通过给@Configuration类加上@EnableAutoConfiguration或者@SpringApplication来自动装载配置

你应该只添加一个@EnableAutoConfiguration在你的应用中,通常我们建议添加到主类中.也就是启动类`.

逐渐取消自动配置

自动配置是非侵入性的,你可以随时使用自定义配置来替换它特定的部分.

如果你想知道应用使用了哪些自动配置,可以使用-- debug开关启动你的应用程序,控制台会输出自动配置的报告记录.

禁用特定的自动配置

如果你有不需要的自动配置,你可以通过@EnableAutoConfiguration中的exclude属性将其禁用.

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属性控制要配出的自动配置类列表

Spring Beans 和依赖注入

我们可以使用@ComponentScan来需找你的beans,并结合@Autowired使用构造函数注入效果会更好

如果你按上述建议构建了代码(将应用程序类放在根目录下),你可以添加一个不带任何参数的@ComponentScan,你的所有的组件(@Component,@Service,@Repository,@Controller等)都将会自动注册为Spring Bean

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

    // ...

}
@Service
public class DatabaseAccountService implements AccountService {

    private final RiskAssessor riskAssessor;

    public DatabaseAccountService(RiskAssessor riskAssessor) {
        this.riskAssessor = riskAssessor;
    }

    // ...

}

需要注意的是构造函数的方法来注入

@Service
public class AccountService {
    private final UserService userService;
    private final PermissionService permissionService;
    private final CacheManager cacheManager;

    public AccountService(final UserService userService, final PermissionService permissionService, final CacheManager cacheManager) {
        this.userService = userService;
        this.permissionService = permissionService;
        this.cacheManager = cacheManager;
    }
}

使用 @SpringApplication 注解

许多Spring Boot 开发人员主类总是带有@Configuration, @EnableAutoConfiguration@ComponentScan. 这几个注解通常会一起使用,因为我们提供了一中方便的@SpringApplication注解

@SpringApplication包含的这些所有的注解

package com.example.myproject;

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

}
/*
 * Copyright 2012-2019 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.boot.autoconfigure;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.context.TypeExcludeFilter;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.core.annotation.AliasFor;
import org.springframework.data.repository.Repository;

/**
 * Indicates a {@link Configuration configuration} class that declares one or more
 * {@link Bean @Bean} methods and also triggers {@link EnableAutoConfiguration
 * auto-configuration}, {@link ComponentScan component scanning}, and
 * {@link ConfigurationPropertiesScan configuration properties scanning}. This is a
 * convenience annotation that is equivalent to declaring {@code @Configuration},
 * {@code @EnableAutoConfiguration}, {@code @ComponentScan}.
 *
 * @author Phillip Webb
 * @author Stephane Nicoll
 * @author Andy Wilkinson
 * @since 1.2.0
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
		@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {

	/**
	 * Exclude specific auto-configuration classes such that they will never be applied.
	 * @return the classes to exclude
	 */
	@AliasFor(annotation = EnableAutoConfiguration.class)
	Class<?>[] exclude() default {};

	/**
	 * Exclude specific auto-configuration class names such that they will never be
	 * applied.
	 * @return the class names to exclude
	 * @since 1.3.0
	 */
	@AliasFor(annotation = EnableAutoConfiguration.class)
	String[] excludeName() default {};

	/**
	 * Base packages to scan for annotated components. Use {@link #scanBasePackageClasses}
	 * for a type-safe alternative to String-based package names.
	 * <p>
	 * <strong>Note:</strong> this setting is an alias for
	 * {@link ComponentScan @ComponentScan} only. It has no effect on {@code @Entity}
	 * scanning or Spring Data {@link Repository} scanning. For those you should add
	 * {@link org.springframework.boot.autoconfigure.domain.EntityScan @EntityScan} and
	 * {@code @Enable...Repositories} annotations.
	 * @return base packages to scan
	 * @since 1.3.0
	 */
	@AliasFor(annotation = ComponentScan.class, attribute = "basePackages")
	String[] scanBasePackages() default {};

	/**
	 * Type-safe alternative to {@link #scanBasePackages} for specifying the packages to
	 * scan for annotated components. The package of each class specified will be scanned.
	 * <p>
	 * Consider creating a special no-op marker class or interface in each package that
	 * serves no purpose other than being referenced by this attribute.
	 * <p>
	 * <strong>Note:</strong> this setting is an alias for
	 * {@link ComponentScan @ComponentScan} only. It has no effect on {@code @Entity}
	 * scanning or Spring Data {@link Repository} scanning. For those you should add
	 * {@link org.springframework.boot.autoconfigure.domain.EntityScan @EntityScan} and
	 * {@code @Enable...Repositories} annotations.
	 * @return base packages to scan
	 * @since 1.3.0
	 */
	@AliasFor(annotation = ComponentScan.class, attribute = "basePackageClasses")
	Class<?>[] scanBasePackageClasses() default {};

	/**
	 * Specify whether {@link Bean @Bean} methods should get proxied in order to enforce
	 * bean lifecycle behavior, e.g. to return shared singleton bean instances even in
	 * case of direct {@code @Bean} method calls in user code. This feature requires
	 * method interception, implemented through a runtime-generated CGLIB subclass which
	 * comes with limitations such as the configuration class and its methods not being
	 * allowed to declare {@code final}.
	 * <p>
	 * The default is {@code true}, allowing for 'inter-bean references' within the
	 * configuration class as well as for external calls to this configuration's
	 * {@code @Bean} methods, e.g. from another configuration class. If this is not needed
	 * since each of this particular configuration's {@code @Bean} methods is
	 * self-contained and designed as a plain factory method for container use, switch
	 * this flag to {@code false} in order to avoid CGLIB subclass processing.
	 * <p>
	 * Turning off bean method interception effectively processes {@code @Bean} methods
	 * individually like when declared on non-{@code @Configuration} classes, a.k.a.
	 * "@Bean Lite Mode" (see {@link Bean @Bean's javadoc}). It is therefore behaviorally
	 * equivalent to removing the {@code @Configuration} stereotype.
	 * @since 2.2
	 * @return whether to proxy {@code @Bean} methods
	 */
	@AliasFor(annotation = Configuration.class)
	boolean proxyBeanMethods() default true;

}

@SpringBootApplication还提供别名以自定义@EnableAutoConfiguration和@ComponentScan的属性。

启动你的应用

将应用程序打包为jar并使用嵌入式HTTP服务器是Spring Boot最大优势之一.

启动你的打包应用


java -jar target/myproject-0.0.1-SNAPSHOT.jar

也可以在启用了远程调试支持的情况下运行打包的应用程序。这使您可以将调试器附加到打包的应用程序:

java -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=8000,suspend=n \
       -jar target/myproject-0.0.1-SNAPSHOT.jar

使用Maven Plugin

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

mvn spring-boot:run

您可能还想使用有用的操作系统环境变量:

export MAVEN_OPTS=-Xmx1024m

Spring Boot 的功能

@SpringApplication

SpringApplication 提供了便捷的启动方式,将使用main()方法来启动Spring应用,大多数情况下只能委托给SpringApplication.run方法

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

启动失败

如果启动失败,已注册的FailureAnalyzers将会有机会提供专门的错误消息和解决该问题的具体措施

***************************
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.

Spring Boot 提供了大量的FailureAnalyzers实现,你可以轻松的添加
自己的实现

如果错误分析器没有捕获异常,你任然可以显示完整的自动配置的报告,可以让你更好了解发生了什么问题.

你需要为org.springframework.boot.autoconfigure.logging.AutoConfigurationReportLoggingInitializer启动debug属性或者启动DEBUG日志记录

如果你使用的是java -jar来启动应用,你可以添加debug属性

$ java -jar myproject-0.0.1-SNAPSHOT.jar --debug

自定义Banner

你可以通过添加banner.txt文件到你的项目路径来更换应用启动时打印的logo.或者设置banner.location指向你的文件位置.(如果出现文件编码异常,可以使用banner.charset来设置.默认为UTF-8).除了txt文件外,还可以将图像文件gif,jpg,png添加到项目路径或者设置banner.image.location属性.这些图片将会转化为ASCII艺术作品并打印在任何文字上方.

banner.txt你可以使用以下任意占位符

VariableDescription

${application.version}

The version number of your application as declared in MANIFEST.MF. For example Implementation-Version: 1.0 is printed as 1.0.

${application.formatted-version}

The version number of your application as declared in MANIFEST.MF formatted for display (surrounded with brackets and prefixed with v). For example (v1.0).

${spring-boot.version}

The Spring Boot version that you are using. For example 2.0.0.M3.

${spring-boot.formatted-version}

The Spring Boot version that you are using formatted for display (surrounded with brackets and prefixed with v). For example (v2.0.0.M3).

${Ansi.NAME} (or ${AnsiColor.NAME}, ${AnsiBackground.NAME}, ${AnsiStyle.NAME})

Where NAME is the name of an ANSI escape code. See AnsiPropertySource for details.

${application.title}

The title of your application as declared in MANIFEST.MF. For example Implementation-Title: MyApp is printed as MyApp.

如果你使用代码的方式实现Banner,你可以使用SpringApplication.setBanner().也可以使用org.springframework.boot.Banner接口实现你的printBanner()方法

您还可以使用spring.main.banner-mode属性来确定是否必须使用配置的记录器(log)将横幅打印在System.out(console)上,或者根本不打印(off

YAML的设置

spring:
    main:
        banner-mode: "off"

自定义的SpringApplication

如果你不喜欢SpringApplication的默认设置,你也可以创建一个本地实例来启动Spring Boot应用

public static void main(String[] args) {
    SpringApplication app = new SpringApplication(MySpringConfiguration.class);
    app.setBannerMode(Banner.Mode.OFF);
    app.run(args);
}

这里传递给SpringApplication的构造函数式Spring Bean的配置源.通常情况下它将是对@Configuration类的引用,或者是XML的配置或者是应扫描的包引用

同样我们也可以使用application,properties文件来配置SpringApplication.详细请参照
Chapter 24, Externalized Configuration 外部化配置.

有关配置选项的完整列表,请参见SpringApplication Javadoc

流式构建 API

如果你需要构建ApplicationContext层级结构(具有父/子关系的多个上下文),或者只是喜欢流式构造的API,则可以使用SpringApplicationBuilder

SpringApplicationBuilder 允许将多个方法调用链接在一起,并允许创建层次结构的父方法和子方法

new SpringApplicationBuilder()
        .sources(Parent.class)
        .child(Application.class)
        .bannerMode(Banner.Mode.OFF)
        .run(args);

创建ApplicationContext层级结构的时候会有一些限制,例如:Web组件必须包含在子上下文中,并且相同的环境将用于父上下文和子上下文.更多纤细请看SpringApplicationBuilder
Javadoc

Application 的事件和监听器

除了通产的Spring Framework事件(例如:ContextRefreshedEvaent)之外,SpringApplication还发送一些其他的application事件

实际上在创建ApplicationContext之前会触发一些事件,所以你不能这些监听器为@Bean,你可以通过SpringApplication.addListeners(..)或者SpringApplicationBuilder.listeners(..)方法注册它们.如果你不想管应用程序如何自动注册那些监听器.你可以使用1META-INF / spring.factories1文件添加到项目中,并使用1org.springframework.context.ApplicationListener1键引用您的监听器。

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

应用的事件必须按下列顺序发送

- ApplicationStartingEvent .在运行开始时发送,但是在有任何操作之前,除了监听器和初始化注册器的初始化之外.

- ApplicationEnvironmentPreparedEvent 需要在一直上下文的Environment中使用,但是需要上下文已经创建

- ApplicationPreparedEvnet 在刷新开始之前但是在Bean定义加载之后发送

- ApplicationReadyEvent 在刷新并处理所有的相关回调后,应用程序已准备好处理请求后发送

- ApplicationFailedEvent 在应用启动失败时发送

通常不需要使用应用程序事件,但是了解它们的存在可以让你对Spring Boot的内部更加了解

web 环境

SpringApplication 将会创建正确类型的ApplicationContext.在默认情况下,将使用AnnotationConfiguApplication 或者 AnnotaionConfigServletWebApplicationContext,具体取决于是否是web应用

确定是否web 环境所使用的的算法非常简单,如果你需要调整默认值你可以使用setWebEnvironment(boolean webEnvironment),也可以使用setApplicationContextClass(...)来控制ApplicationContext 的类型

通常在JUnit测试中使用Application时,可以使用setWebEnvironment(false)

访问应用参数

如果你需要传递参数给SpringApplication.run(..),你可以注入org.springframework.boot.ApplicationArgumentsbean.ApplicationArguments接口提供了对原始String[]参数和已解析的选项和非选项参数的访问

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"]
    }

}

Spring Boot 还将在Spring Environment中注册一个CommandLinePropertySource,它允许你使用@Value注解来注入单个应用参数

使用SpringApplicationRunner 或者 CommandLineRunner

如果你需要在SpringApplication启动完成之前加载一些代码,你尅实现ApplicationRunner接口或者CommandLineRunner接口,并实现一个run 方法,它会在SpringApplication.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 Bean,则可以另外实现org.springframework.core.Ordered接口或使用org.springframework.core.annotation.Order注释。

结束应用

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

@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()方法提供的退出代码。

管理员功能

应用管理员功能可以通过指定spring.application.admin.enabled属性来管理.在公开平台MBeanServer上的SpringApplicationAdminMXBean。您可以使用此功能来远程管理Spring Boot应用程序。

如果你想知道应用程序在HTTP哪个端口上运行可以输入local.server.prot

MBean会公开一钟关闭应用程序的方法,请小心使用

外部配置

Spring Boot 允许外部配置,以便可以再不同的环境中使用相同的应用程序.你可以使用属性文件,YANL文件,环境变量和命令行参数来进行操作外部配置

可以使用@Value注解将属性直接注入到bean中,还可以通过Spring的抽象环境,也可以通过@ConfigurationProperties绑定到结构化对象

Spring Boot 使用一个非常特殊的PropertySource顺序,你需要按下列的顺序来合理覆盖值

  • 您的主目录上的Devtools全局设置属性(在devtools处于活动状态时,为〜/ .spring-boot-devtools.properties)

  • 测试时使用的@TestPropertySource注解。

  • 测试时使用的@TestPropertySource#properties注解。

  • 命令行参数

  • 来自SPRING_APPLICATION_JSON的属性(嵌入在环境变量或系统属性中的内联JSON)

  • ServletConfig 初始化参数

  • ServletContext 初始化参数

  • 来自java:comp/env的JDNI参数

  • Java系统属性(System.getProperties())

  • 操作系统环境变量

  • 一个RandomValuePropertySource,它只有一个配置在random.*

  • 打包的jar之外的配置文件(application- {profile} .properties和YAML变体)

  • 打包的jar包之内的配置文件(application- {profile} .properties和YAML变体)

  • 打包的jar之外的应用程序属性(application.properties和YAML变体)

  • 打包在jar中的应用程序属性(application.properties和YAML变体)

  • @Configuration类上的@Properties注解

  • 默认属性 (使用SpringApplication.setDefaultProperties指定)

假设您开发了一个使用name属性的@Component

import org.springframework.stereotype.*
import org.springframework.beans.factory.annotation.*

@Component
public class MyBean {

    @Value("${name}")
    private String name;

    // ...

}

在你的应用程序的路径上(例如:在jar中),你可以使用application.properties来给name设置一个默认值.在新环境中运行时,可以在jar外部提供application.properties,以覆盖name.你也可以在启动命令时添加一个临时参数java -jar app.jar --name="Spring"

SPRING_APPLICATION_JSON 在UNIX中的配置

SPRING_APPLICATION_JSON='{"foo":{"bar":"spam"}}' java -jar myapp.jar

java -Dspring.application.json='{"foo":"bar"}' -jar myapp.jar

java -jar myapp.jar --spring.application.json='{"foo":"bar"}'

JNDI 的示例: java:comp/env/spring.application.json

配置随机值

RandomValuePropertySource可用于注入随机值(例如,注入机密或测试用例)。它可以产生整数,longs,uuid或字符串

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]}

访问命令行属性

默认情况下,SpringApplication会将所有命令行选项参数(以“-”开头,例如–server.port = 9000)转换为属性,并将其添加到Spring Environment中,命令行属性始终优先于其他属性源

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

属性文件

SpringApplication将在以下位置从application.properties文件加载属性,并将其添加到Spring Environment(注意优先级也如下)

  • 当前目录的/config的子目录

  • 当前目录

  • 类路径/config

  • 根路径

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

你也可以使用spring.config.namespring.config.location来配置你的环境变量

$ java -jar myproject.jar --spring.config.name=myproject

//或者

$ java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties

spring.config.namespring.config.location 加载的顺序比较早,所以需要确定加载哪些文件,这些就必须要定义为环境变量(通常为系统换将变量,系统属性或者命令行参数)

如果spring.config.name之后跟的是目录(不是文件),那就应该是 / 结尾.spring.config.location中指定的文件按原样使用,不支持特定于配置文件的变体,并且将被任何特定于配置文件的属性覆盖。

配置的位置的搜索顺序相反.默认情况下是classpath:/,classpath:/config/,file:./,file:./config/.而实际上的搜索顺序为

1.file:./config/

2.file:./

3.classpath:/config/

4.classpath:/

在自定义配置后,除了默认位置的顺序,还会使用以上顺序,在默认位置之前搜索自定义位置。例如,如果配置了自定义位置classpath:/ custom-config /,file:./ custom-config /,则搜索顺序变为:
1.file:./custom-config/

2.classpath:custom-config/

3.file:./config/

4.file:./

5.classpath:/config/

6.classpath:/

通过此搜索顺序,您可以在一个配置文件中指定默认值,然后在另一个配置文件中有选择地覆盖这些值

配置文件的特殊属性

可以使使用application-{profile}.properties的命名方式给application.properties定义.如果未定义将会以默认方式application-default.properties加载

所有的配置都是后来的覆盖前面的(后赢策略)

如果您在spring.config.location中指定了任何文件,则不会考虑这些文件的任何特殊属性。如果您还想使用配置文件的特殊属性,请使用spring.config.location中的目录。

属性中的占位符

使用application.properties中的值时,它们会通过现有环境进行过滤,因此您可以引用以前定义的值(例如,从System属性中)。

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

您还可以使用这种技术来创建现有Spring Boot属性的“Short”变体。有关详细信息,请参见Section 73.4, “Use ‘short’ command line arguments”

使用YAML文件

YAML 是JSON的超集,因此是指定分层配置数据的一中非常方便的格式.只要在应用类路径上有Snake YAML库就会自动支持YAML作为属性的替代方法.

spring-boot-starter 将自动提供SnakeYAML

加载YAML

Spring Framework提供了两个类来加载YAML文档.YamlPropertiesFactoryBean就会把YAML当做一个属性加载,YamlMapFactoryBean就会把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]解引用器表示为属性键,例如,以下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;
    }
}

YAML如果配置Spring的环境变量

YamlPropertiesSourceLoader类可以使用YAML作为配置源来适用各种Spring环境.它允许使用@Value注解和占位符语法来访问YAML属性.

server:
    address: 192.168.1.100
---
spring:
    profiles: development
server:
    address: 127.0.0.1
---
spring:
    profiles: production
server:
    address: 192.168.1.120

如上述配置,当spring.profiles为开发,生产或者默认时,server.address将会采取不同的ip地址

YAML的缺点

无法通过@PropertySource注释加载YAML文件。因此,如果您需要以这种方式加载值,则需要使用属性文件

合并YAML列表

YAML的任何内容都会被转换为属性.

例如,假设MyPojo对象的名称和描述属性默认为空。让我们从FooProperties中公开MyPojo的列表:

@ConfigurationProperties("foo")
public class FooProperties {

    private final List<MyPojo> list = new ArrayList<>();

    public List<MyPojo> getList() {
        return this.list;
    }

}

我们拥有以下配置

foo:
  list:
    - name: my name
      description: my description
---
spring:
  profiles: dev
foo:
  list:
    - name: my another name

在多个配置文件中指定一个集合时,将使用优先级最高的一个(并且仅使用那个)

如果未指定Spring应用的环境为dev,那么就会使用默认配置,也就是foonamemy another name

安全类型属性的配置

使用@Value注解来批量注入属性通常会很麻烦.特别是你使用多个属性货数据本质上分层的.Spring Boot提供了一种使用属性的替代方法,该方法允许强类型的Bean来管理和验证应用程序的配置.

package com.example;

import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties("foo")
public class FooProperties {

    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) { ... }

    }
}

您还需要列出要在@EnableConfigurationProperties批注中注册的属性类:

@Configuration
@EnableConfigurationProperties(FooProperties.class)
public class MyConfiguration {
}

其实这个东西就有点像代理模式,不允许随便使用配置文件中的配置属性,它必须通过具有@EnableConfigurationProperties批注中注册的属性类来注册

第三方配置

除了使用ConfigurationProperties注解之外,还可以使用@Bean注解在公共的方法在.这会在使用三方属性时起到作用

@ConfigurationProperties(prefix = "bar")
@Bean
public BarComponent barComponent() {
    ...
}

bar前缀定义的任何属性都将以与上面的FooProperties示例类似的方式映射到该BarComponent bean

自由的绑定

Spring Boot使用一些简单的规则将环境属性绑定到@ConfigurationProperties bean.因此,环境属性名称和Bean属性名称之间不比完全匹配.常使用虚线分割(例如:context-path绑定到contextPath)和大小写区分

例如:

@ConfigurationProperties(prefix="person")
public class OwnerProperties {

    private String firstName;

    public String getFirstName() {
        return this.firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

}
PropertyNote

person.firstName

标准的驼峰语法.

person.first-name

Kebab-case,建议在 .properties.yml files.中使用

person.first_name

下划线表示法, 用于 .properties.yml files.的替代格式。

PERSON_FIRSTNAME

大写格式。在使用系统环境变量时推荐使用.

prefix值的前缀必须是 Kebab-case,必须由小写字母开头和 - 分隔

每个配置源的绑定规则

Table 24.2. relaxed binding rules per property source

Property SourceSimpleList

Properties Files

Camel-case, kebab-case or underscore notation

Standard list syntax using [ ] or comma-separated values

YAML Files

Camel-case, kebab-case or underscore notation

Standard YAML list syntax or comma-separated values

Environment Variables

Upper case format with underscore as the delimiter. _ should not be used within a property name

Numeric values surrounded by underscores. eg: MY_FOO_1_BAR = my.foo[1].bar

System properties

Camel-case, kebab-case or underscore notation

Standard list syntax using [ ] or comma-separated values

我们建议,如果可能,属性以小写的kebab格式存储。即 my.property-name = foo

属性转换

当Spring绑定到@ConfigurationProperties bean时,它将尝试将外部应用程序属性强制为正确的类型。

如果需要自定义类型转换,则可以提供一个ConversionService bean(具有bean id conversionService)或自定义属性编辑器(通过CustomEditorConfigurer bean)或者定制转换器(bean定义标注为@ConfigurationPropertiesBinding

在应用的生命周期中ConversionService很早就被请求,请注意使用的依赖项.通常,您需要的任何依赖项可能在创建时未完全初始化.如果配置键强制不需要自定义的转换服务,而您只想重命名具有@ConfigurationPropertiesBinding的自定义转换器,则可能需要重命名自定义的转换服务

@ConfigurationProperties验证

如果使用@Validated配合@ConfigurationProperties一起使用时Spring Boot将会对其验证.
您可以在配置类上直接使用JSR-303 javax.validation约束注释。只需确保您的类路径上有兼容的JSR-303实现即可

@ConfigurationProperties(prefix="foo")
@Validated
public class FooProperties {

    @NotNull
    private InetAddress remoteAddress;

    // ... getters and setters

}

当你需要组合嵌套效验时,必须将使用@Valid注解才能触发:

@ConfigurationProperties(prefix="connection")
@Validated
public class FooProperties {

    @NotNull
    private InetAddress remoteAddress;

    @Valid
    private final Security security = new Security();

    // ... getters and setters

    public static class Security {

        @NotEmpty
        public String username;

        // ... getters and setters

    }

}

你也可以创建一个名为configurationPropertiesValidator的bean来自自定义Spring Validator.这个@Bean方法必须为静态的.配置竖向验证器是在应用程序生命周期早期创建的,并且将@Bean方法声明为允许静态创建bean,所以无需实例化@Configuration

spring-boot-actuator模块包括一个公开所有@ConfigurationProperties bean的端点。只需将您的Web浏览器指向/ configprops或使用等效的JMX端点即可。请参阅Production ready features。详细信息

@ConfigurationProperties 和@Value

@Value是核心容器功能,它没有提供与类型安全的配置属性相同的功能。下表总结了@ConfigurationProperties@Value支持的功能

Feature@ConfigurationProperties@Value

Relaxed binding

Yes

No

Meta-data support

Yes

No

SpEL evaluation

No

Yes

如果您为自己的组件定义了一组配置键,我们建议您将它们组合在以@ConfigurationProperties注解的POJO中。
另请注意,由于@Value不支持简单的绑定,因此如果您需要使用环境变量来提供值,则不是一个很好的选择

最后,尽管您可以在@Value中编写SpEL表达式,但不会从Application
property files
中处理此类表达式。

Profiles(轮廓, 剖面, 侧面)

Spring Profiles提供了一种分离应用程序配置的部分并使之仅在某些环境中可用的方法.任何@Component@Configuration都可以用@Profile标记,以限制加载时间:

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

    // ...

}

以正常的Spring方式,您可以使用spring.profiles.activeEnvironment属性指定哪些配置文件处于活动状态。您可以通过任何常用方式指定属性,例如,可以将其包含在application.properties中:

spring.profiles.active=dev,hsqldb

或使用命令行上指定--spring.profiles.active = dev,hsqldb开关

添加活动配置文件

spring.profiles.active属性遵循与其他属性相同的排序规则,级别最高的PropertySource将获胜。这意味着您可以在application.properties中指定活动配置文件,然后使用命令行开关替换它们。

例如,当使用开关--spring.profiles.active = prod运行具有以下属性的应用程序时,proddbprodmq配置文件也将被激活:

---
my.property: fromyamlfile
---
spring.profiles: prod
spring.profiles.include:
  - proddb
  - prodmq

可以在YAML文档中定义spring.profiles属性,以确定何时将该特定文档包括在配置中。有关更多详细信息,请参Section 73.7, “Change configuration depending on the environment”

代码的方式设置配置文件

您可以在应用程序运行之前通过调用SpringApplication.setAdditionalProfiles(…)以编程方式设置活动配置文件。也可以使用Spring的ConfigurableEnvironment接口激活配置文件。

特定文件的配置文件

加载文件时,会将application.properties(或application.yml)和通过@ConfigurationProperties引用的文件的特定于配置文件的变体视为文件。有关详细信息,请参见第24.4节Section 24.4, “Profile-specific properties”

日志

Spring Boot 使用Commons Logging进行所有的内部日志记录.但是日志的底层实现提供了Java Util Logging,log4J2,Logback的默认配置.

默认情况下,如果您使用“启动器”,则将使用Logback进行日志记录。还包括适当的Logback路由,以确保使用Java Util日志记录,Commons LoggingLog4JSLF4J的从属库都能正常工作。

日志格式

默认的日志格式:

2014-03-05 10:57:51.112  INFO 45469 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/7.0.52 
2014-03-05 10:57:51.253  INFO 45469 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2014-03-05 10:57:51.253  INFO 45469 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1358 ms
2014-03-05 10:57:51.698  INFO 45469 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean        : Mapping servlet: 'dispatcherServlet' to [/]
2014-03-05 10:57:51.702  INFO 45469 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]

日记将会输出以下类型:

  • 日期和时间 毫秒级精度,易于排序

  • 日志等级 ERROR,WRAN,INFO,DEBUG,TRACE

  • 进程ID

  • 分隔符 --- 用于区分时间日志消息的开始

  • 线程名称 用方括号括起来(对于控制台输出可能会被截断)

  • 记录器名称-通常是源类名称(通常是缩写)

  • 日志消息

Logback 没有FATAL级别的日志,它被归纳到ERROR日志中

控制台输出

认日志配置将在编写消息时将消息回显到控制台。默认情况下,将记录ERRORWARNINFO级别的消息。您还可以通过使用--debug标志启动应用程序来启用“调试”模式。

$ java -jar myapp.jar --debug

你也可以使用application.properties中配置debug=true

启用调试模式后,将配置一些核心记录器(嵌入式容器,Hibernate和Spring Boot)以输出更多信息。启用调试模式不会将您的应用程序配置为记录所有具有DEBUG级别的消息。

另外,您可以通过使用--trace标志(或application.properties中的trace = true)启动应用程序来启用“TRACE”模式。

日志颜色

如果您的终端支持ANSI,则将使用彩色输出来提高可读性。您可以将spring.output.ansi.enabled设置为supported value,以覆盖自动检测。

使用%clr转换字配置颜色编码。转换器将以最简单的形式根据对数级别为输出着色,例如:

%clr(%5p)

日志级别对应的颜色:

LevelColor

FATAL

Red

ERROR

Red

WARN

Yellow

INFO

Green

DEBUG

Green

TRACE

Green

另外,您可以通过将其提供为转换的选项来指定应使用的颜色或样式。例如,将文本设为黄色

%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){yellow}

支持以下颜色和样式:

  • blue
  • cyan
  • faint
  • green
  • magenta
  • red
  • yellow

文件输出日志

默认情况下,Spring Boot将仅登录到控制台,并且不会写入日志文件。如果除了控制台输出外还想写日志文件,则需要设置logging.filelogging.path属性(例如,在application.properties中配置)。

logging.filelogging.pathExampleDescription

(none)

(none)

 

Console only logging.

Specific file

(none)

my.log

Writes to the specified log file. Names can be an exact location or relative to the current directory.

(none)

Specific directory

/var/log

Writes spring.log to the specified directory. Names can be an exact location or relative to the current directory.

日志文件达到10 MB时将覆盖,并且与控制台输出一样,默认情况下会记录ERRORWARNINFO级别的消息。

日志记录系统在应用程序生命周期的早期进行了初始化,因此在通过@PropertySource批注加载的属性文件中找不到此类日志记录属性。

日志记录属性独立于实际的日志记录基础结构。结果,特定的配置键(例如Logback的logback.configurationFile)不是由Spring Boot管理的。

日志等级

日志等级支持使用Spring 环境或者其他方式(application.properties)来进行配置.loggin.level.*= {LEVEL},其中的{LEVEL}可以使用TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF.

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

默认情况下,Spring Boot重映射Thymeleaf INFO消息,以便它们以DEBUG级别记录。这有助于减少标准日志输出中的噪声。有关如何在自己的配置中应用重新映射的详细信息,请参见LevelRemappingAppender

自定义日志配置

你可以通过类路径来激活不同的日志记录系统,并通过根目录中或者Spring Environment属性的logging.config指定适当的配置文件来自定义各种日志记录系统.

根据您的日志记录系统,将加载以下文件:

Logging SystemCustomization

Logback

logback-spring.xml, logback-spring.groovy, logback.xml or logback.groovy

Log4j2

log4j2-spring.xml or log4j2.xml

JDK (Java Util Logging)

logging.properties

如果可能,我们建议您在日志配置中使用-spring变体(例如logback-spring.xml而不是logback.xml)。如果使用标准配置位置,Spring将无法完全控制日志初始化。

从“可执行jar”运行时,Java Util Logging存在一些已知的类加载问题,这些问题会导致出现问题。我们建议您尽可能避免使用它。

为了自定义,其他一些属性从Spring Environment转移到System属性:

Spring EnvironmentSystem PropertyComments

logging.exception-conversion-word

LOG_EXCEPTION_CONVERSION_WORD

The conversion word that’s used when logging exceptions.

logging.file

LOG_FILE

Used in default log configuration if defined.

logging.path

LOG_PATH

Used in default log configuration if defined.

logging.pattern.console

CONSOLE_LOG_PATTERN

The log pattern to use on the console (stdout). (Only supported with the default logback setup.)

logging.pattern.file

FILE_LOG_PATTERN

The log pattern to use in a file (if LOG_FILE enabled). (Only supported with the default logback setup.)

logging.pattern.level

LOG_LEVEL_PATTERN

The format to use to render the log level (default %5p). (Only supported with the default logback setup.)

PID

PID

The current process ID (discovered if possible and when not already defined as an OS environment variable).

Logback 拓展

pring Boot包含许多Logback扩展,可以帮助进行高级配置。您可以在logback-spring.xml配置文件中使用这些扩展名。

您无法在标准logback.xml配置文件中使用扩展名,因为扩展名加载时间过早。您需要使用logback-spring.xml或定义logging.config属性。

这些扩展不能与Logback的配置扫描一起使用。如果尝试这样做,则对配置文件进行更改将导致类似于以下记录之一的错误:

ERROR in ch.qos.logback.core.joran.spi.Interpreter@4:71 - no applicable action for [springProperty], current ElementPath is [[configuration][springProperty]]
ERROR in ch.qos.logback.core.joran.spi.Interpreter@4:71 - no applicable action for [springProfile], current ElementPath is [[configuration][springProfile]]
特殊的文件配置

<springProfile>标签允许您根据活动的Spring概要文件有选择地包括或排除配置部分。在<configuration>元素内的任何位置都支持概要文件部分。使用name属性指定哪个配置文件接受配置。可以使用逗号分隔的列表指定多个配置文件。<springProfile name =“ staging”>

<springProfile name="staging">
    <!-- configuration to be enabled when the "staging" profile is active -->
</springProfile>

<springProfile name="dev, staging">
    <!-- configuration to be enabled when the "dev" or "staging" profiles are active -->
</springProfile>

<springProfile name="!production">
    <!-- configuration to be enabled when the "production" profile is not active -->
</springProfile>
环境特性

配合环境变量或者application.properties使用

<springProperty scope="context" name="fluentHost" source="myapp.fluentd.host"
        defaultValue="localhost"/>
<appender name="FLUENT" class="ch.qos.logback.more.appenders.DataFluentAppender">
    <remoteHost>${fluentHost}</remoteHost>
    ...
</appender>

欢迎关注我的公众号在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值