文章目录

  • Part III. Using Spring Boot
  • Part IV Spring Boot Features
    • 23 SpringApplication
      • 23.1 Startup Failure
      • 23.2 Customizing the Banner
      • 23.3 Customizing SpringApplication
      • 23.4 Fluent Builder API
      • 23.5 Application Events and Listeners
      • 23.7 Accessing Application Arguments
      • 23.8 Using the ApplicationRunner or CommandLineRunner
      • 23.10 Admin Features
    • 24 Externalized Configuration
      • 24.1 Configuring Random Value
      • 24.2 Accessing Command Line Properties
      • 24.3 Application Property Files
      • 24.4 Profile-specific Properties
      • 24.5 Placeholders in Properties
      • 24.6 Encrypting Properties
      • 24.7 Using YAML Instead of Properties
      • 24.8 Type-safe Configuration Properties
    • 25 Profiles
    • 26 Logging
      • 26.1 Log Format
      • 26.2 Console Output
      • 26.3 File Output
      • 26.4 Log Levels
      • 26.5 Log Groups
      • 26.6 Custom Log Configuration
      • 26.7 Logback Exetensions
    • 28 JSON
      • 28.1 Jackson
      • 28.2 Gson
    • 29 Developing Web Applications
      • 29.1 The "Spring Web MVC Framework"
      • 29.4 Embedded Servlet Container Support
    • 30 Security
      • 30.1 MVC Security
      • Spring Security架构
      • Spring Security OAuth2
      • 30.4 Actuator Security
    • 31 Working with SQL Database
      • 31.1 Configure a DataSource
      • 31.2 Using JdbcTemplate
      • 31.3 JPA and Spring Data JPA
      • 31.4 Spring Data JDBC
      • 31.5 Using H2's Web Console
      • 31.6 Using JOOQ
    • 32 Working with NoSQL Technologies
      • 32.1 Redis
      • 32.2 MongoDB
      • 32.3 Neo4j
      • 32.6 Elasticsearch
      • 32.9 LDAP
    • 33 Caching
      • 33.1 Supported Cache Providers
    • 34 Messaging
      • 34.1 JMS
      • 34.2 AMQP
      • 34.3 Apache Kafka
    • 35 Calling REST Services with RestTemplate
      • 35.1 RestTemplate Customization
    • 37 Validation
    • 38 Sending Email
    • 39 Distributed Transactions with JTA
      • 39.1 Using an Atomikos Transaction Manager
      • 39.2 Using a Bitronix Transaction Manager
      • 39.3 Using a Java EE Managed Transaction Manager
      • 39.4 Mixing XA and Non-XA JMS Connection
    • 41 Quatz Scheduler
    • 42 Task Execution and Scheduling
    • 43 Spring Integration
    • 44 Spring Session
    • 45 Monitoring and Management over JMX
      • 49 Creating Your Own Auto-configuration
  • Part V Spring Boot Actuator: Production-ready features
    • 52 Enabling Production-ready Features
    • 53 Endpoints
    • 54 Monitoring and Management over HTTP
    • 56 Loggers
    • 结构

基于springboot 2.1.5.RELEASE官方文档。

Part III. Using Spring Boot

spring.http.log-request-detail,打印请求详细信息
spring.devtools.restart.exclude,修改时不重启的路径

Part IV Spring Boot Features

23 SpringApplication

23.1 Startup Failure

FailureAnalyzer,展示错误信息、解决方案
如无对应分析器,可开启调试模式debug property,或打开调试日志DEBUG logging。
jar包开启:java -jar A.jar --debug
配置文件:debug=true
日志设置:logging.level.<logName>=level

23.2 Customizing the Banner

classpath下放置banner文件,可为:txt、gif、jpg、png。显示时图片在txt上方。
或通过配置文件指定位置:spring.banner.location、spring.banner.image.location
spring.main.banner-mode,banner显示方式;值:console、log、off
yaml将off映射为false,故off须加双引号"off",防转换。

23.3 Customizing SpringApplication

SpringApplication sa = new SpringApplication(Clazz.class);//构建
//sa自定义配置
sa.run(args);//启动

23.4 Fluent Builder API

new SpringApplicationBuilder()//通过builder方式配置、运行;作用同上
.sources()//加载配置类
.child()//加载配置类
.bannerMode()//自定义配置
.run(args);

23.5 Application Events and Listeners

applicationContext创建前事件监听器注册:

  • SpringApplication#addListeners();
  • SpringApplicationBuilder#listeners();

事件顺序:

  • ApplicationStartingEvent;run()方法后。加载spring-boot@META-INF/spring.factories
  • ApplicationEnvironmentPreparedEvent;environment准备完毕;EnvironmentPostProcessor
  • ApplicationPreparedEvent;加载bean definition完毕;BeanFactoryPostProcessor
  • ApplicationStartedEvent;applicationContext准备完毕;BeanPostProcessor
  • ApplicationReadyEvent;ApplicationRunner、CommandLineRunner调用完毕
  • ApplicationFailedEvent;异常

普通事件监听,配置bean;@EventListener,方法注解;或实现ApplicationListener。

23.7 Accessing Application Arguments

ApplicationArguments bean,获取命令行参数,包括:args、配置参数(option)、非配置参数(non-option)
@Value注值解析。

23.8 Using the ApplicationRunner or CommandLineRunner

ApplicationRunner、CommandLineRunner;项目启动后立即回调
ApplicationRunner通过ApplicationArguments获取应用参数。
CommandLineRunner通过args获取应用参数。
规定次序:@Order注解,或实现Order接口。

23.10 Admin Features

spring.application.admin.enabled,暴露SpringApplicationAdminMXBean到jmx。
暴露后可通过jconsole关闭应用。
management.jmx.exposure.exclude;排除shutdown,禁止关闭应用。

24 Externalized Configuration

注入配置值:@Value、@ConfigurationProperties
配置优先级,从高到低:

  1. 命令行参数
  2. 环境变量,包括JVM、OS、JNDI
  3. application配置文件。YAML格式
  4. @PropertySource导入的配置文件。非application名配置文件,${}占位符。。
  5. 程序中配置的默认值

24.1 Configuring Random Value

通过RandomValuePropertySource注入随机值,整形、uuid、字符串:

  • ${random.value};随机字符串
  • ${random.uuid};uuid
  • ${random.int/long};随机值。
  • ${random.int/long(max)},${random.int/long(min,max)};区间值,不包含max。

24.2 Accessing Command Line Properties

SpringBoot自动将“–”开头的命令行参数,解析后加入到Environment。

  • java -jar A.jar --server.port=8088;
  • -key value,设置java命令基本参数
  • -Dkey=value,设置jvm系统属性,value有空格时用双引号括起。
  • -X,扩展内容,JVM参数;如-Xms1024M,-Xmx2048M

禁用命令行参数:

  • SpringApplication.setAddCommandLineProperties(false)

获取值:

  • @Value、ApplicationArguments;注入获取
  • CommandLineRunner、ApplicationRunner;runner回调获取

24.3 Application Property Files

优先级:\config、\、classpath:/config、classpath;\为jar包路径
命令行参数指定:

  • --spring.config.name;指定配置文件名
  • --spring.config.location;指定配置文件位置,多个路径用逗号","隔开

24.4 Profile-specific Properties

spring.profiles.active/include,配置profiles。配置后加载文件名application-{profile}。
spring.config.location值为file,profile失效;为directory,加载spring.config.name-{profile}
maven profile
classpath:config下不同文件夹,通过maven的profile参数指定。
spring的profile只针对application配置文件,maven的profile通过文件夹判定,可区分其他配置文件。
application中引用maven-profile:@NAME@;yml中单引号括起。pom文件中无对应属性时引用失败。

24.5 Placeholders in Properties

配置文件支持占位符:${expr}。只支持引用值,不支持对象。

24.6 Encrypting Properties

实现EnvironmentPostProcessor接口,处理加密属性。需将实现类加入到spring-boot包META-INF/spring.factories,预加载。
通过PropertySource解析?直接替换值,或者包装PropertySource。
jasypt加密;封装PropertySource

24.7 Using YAML Instead of Properties

YamlPropertiesPostProcessor、YamlMapPostProcessor;将yml在enviroment中暴露为properties、map。@Value–properties,@ConfigurationProperties–map
@PropertySource只能导入properties、xml。
—,在同一yml文件中,隔开多个profile。spring.profiles,声明profile,未声明为公共,可合并。
yml对象数组分隔符:“-”
手动读取yml:

  • new Yaml().load();LinkedHashMap
  • new YamlPropertySourceLoader().load();

@PropertySources/@PropertySource;导入配置文件,可使用${}占位符,统一导入路径。

24.8 Type-safe Configuration Properties

@ConfigurationProperties,将值注入bean;对层级结构,可使用Map、内部类接收。配合@EnableConfigurationProperties、@Bean、@Component注册为bean。
@ConfigurationProperties用于bean方法,将属性绑定到第三方组件。调setter注值。
@ConfigurationProperties松散绑定:忽略大小写、转换分隔符(-、_)
属性合并,-分隔的数组不合并;直接替换。
验证:@Validated、@Valid(属性对象)、其他JSR303注解。

25 Profiles

@Profile,配置spring.profiles.active
spring.profiles、application-profileName.yml,定义配置文件的profile
profile表达式:production & (!test | dev)
25.1 Adding Active Profiles
spring.profiles.include、SpringApplication#setAddtionalProfiles();增加profile
25.2 Programmatically Setting Profiles
SpringApplication#setAddtionalProfiles();
25.3 Profile-specific Configuration Files
spring.config.location值为file,profile失效;为directory,加载spring.config.name-{profile}
application-profileName.yml,定义配置文件的profile

26 Logging

SpringBoot使用Commons Logging;JCL。默认提供JUL(java util logging)、Log4j2、logback。
starters使用logback。
配置参数:logging.*
其他日志框架:SLF4J+对应Adapter

26.1 Log Format

典型日志格式:

  • Date and Time;毫秒精度。
  • Log Level;值:ERROR/FATAL、WARN、INFO、DEBUG、TRACE、OFF
  • Process ID
  • Separator;分隔符,如—
  • Thread name
  • Logger name;触发日志的类
  • Log message

26.2 Console Output

日志默认INFO级别,使用DEBUG级别:debug=true;对Container、Hibernate、SpringBoot有效。

26.3 File Output

logging.file、logging.path;指定日志文件,内容默认与console一致。如未指定,则不写日志文件
logging.config,指定日志配置文件位置
日志配置文件不可通过@PropertySource导入;SpringBoot只管理公共配置。

26.4 Log Levels

设置日志级别:logging.level.loggerName: level;

  • logging.level.root: WARN
  • logging.level.org.hibernate: WARN
  • logging.level.ort.springframework.web: INFO

日志级别默认继承父级,直至root。appender级别。

26.5 Log Groups

定义日志组,便于统一管理level。

  • logging.group.myGroup: org.hibernate,org.springframework.web
  • logging.level.myGroup: WARN

springboot预定义日志组:web、sql

26.6 Custom Log Configuration

指定定制配置文件:logging.config
配置文件名建议加"-spring",以使用spring表达式。
日志系统在applicationContext前初始化,故不能使用@PropertySource引入配置文件。

26.7 Logback Exetensions

使用spring对配置文件的扩展,配置文件名改为logback-spring.xml。
使用spring的扩展后,不能使用logback本身的配置扫描读入配置文件。
<springProfile name=profileExpr>;profile相关标签,name为profile值、profile表达式
<springProperty />;导入environment信息。name名称,后续通过占位符引用;source源信息;defaultValue默认值。
springProfile、springProperty标签只能用于logback配置文件增强。

28 JSON

springboot整合了Gson、Jackson、JSON-B,用作HttpMessageConverter;默认使用Jackson。

28.1 Jackson

导入spring-boot-starter-json时,自动导入jackson;自动配置ObjectMapper、XmlMapper。
spring.jackson.*,配置ObjectMapper参数;包括:

  • deserialization.*,DeserializationFeature
  • generator.*,JsonGenerator
  • parser.*,MapperFeature
  • mapper.*,JsonParser
  • serialization.*,SerializationFeature
  • default-property-inclusion,JsonInclude.Include

28.2 Gson

导入Gson时自动配置bean,配置参数:spring.gson.*。
配置GsonBuilderCustomizer bean,配置Gson bean。

29 Developing Web Applications

29.1 The “Spring Web MVC Framework”

spring.mvc,配置mvc
WebMvcConfigurerSupport,配置mvc
HttpMessageConverters
配置HttpMessageConverter:

  • 配置HttpMessageConverters bean;
  • 或通过继承WebMvcConfigurerSupport;

Custom JSON Serializers and Deserializers
@JsonComponent,标记定制JSON序列化;实现JSONSerializer、JSONDeserializer
MessageCodesResolver
处理异常时输出;配置:spring.mvc.message-codes-resolver_format,值:PREFIX_ERROR_CODE、POSTFIX_ERROR_CODE。springboot返回DefaultMessageCodesResolver.Format对象。
Static Content
默认静态资源路径:/static、/public、/resources、/META-INF/resources
WebMvcConfigurerSupport#addResourceHandler();修改资源映射
spring.mvc.static-path-pattern,静态资源url匹配,默认:/**
spring.resources.static-locations,静态资源路径
Welcome Page
搜索顺序:index.html、index template、springboot实现。
Custom Favicon
搜索静态资源路径、classpath下是否有favicon.ico;有则作为应用图标。
spring.mvc.favicon.enabled: false;禁用
Path Matching and Content Negotiation
springboot禁用后缀匹配;/hello.do不匹配/hello
content negotiation配置:

  • spring.mvc.contentnegotiation.favor-parameter: true;通过请求参数确定内容类型
  • spring.mvc.contentnegotiation.parameter-name: contentType;默认为format
  • 例:/send?format=json,内容为json

ConfigurableWebBindingInitializer
绑定参数,可自定义。
Template Engines
默认模板路径:/src/main/resources/templates
Error Handling
自定义异常处理:

  • 实现ErrorController
  • @ControllerAdvice+@ExceptionHandler

Spring HATEOAS
使用超媒体时,自动配置。
CORS Support
配置CORS拦截:

  • @CrossOrigin;标记方法
  • WebMvcConfigurerSupport#addCorsMappings();全局

29.4 Embedded Servlet Container Support

springboot内嵌容器支持:tomcat、jetty、undertow。默认端口8080.
Servlets、Filters and Listeners
使用内嵌容器时,可使用spring bean注册servlet、filter、listener。

  • 注解方式,@ServletComponentScan、@WebServlet、@WebFilter、@WebListener
  • bean方式,ServletRegistrationBean、FilterRegistrationBean、ServletListenerRegistrationBean

自定义Filter,避免设为Ordered.HIGHEST_PRECEDENCE;防止与CharacterFilter冲突
如果Filter包装request,order需小于OrderedFilter.REQUEST_WRAP_FILTER_MAX_ORDER
Customizing Embedded Servlet Containers
配置内嵌容器;server.*;配置文件参数。包括:

  • Network setting;port、address、context-path等
  • session参数;server.servlet.session.*
  • Error management;server.error.*
  • SSL、HTTPcompression等
  • 容器特性参数;server.tomcat.*、server.undertow.*

30 Security

@EnableGlobalMethodSecurity,开启方法级安全
spring security默认:user、随机密码;配置:spring.security.user.name/password

30.1 MVC Security

导包:spring-boot-starter-security
核心:WebSecurityConfigurerAdapter、@EnableWebSecurity、UserDetailsService/UserDetails

Spring Security架构

http://www.spring4all.com/article/433
Authentication认证(身份验证)、Authorization授权(访问控制)。
Design to seperate authentication from authorization。
过滤器实现:UsernamePasswordAuthenticationFilter、AnonymousAuthenticationFilter、ExceptionTranslationFilter、FilterSecurityInterceptor
Authentication
核心:AuthenticatonManager/ProviderManager、AuthenticationProvider、Authentication
定制:继承WebSecurityConfigurerAdapter,重写configure(),通过AuthenticationManagerBuilder定制local AuthenticationManager。
UserDetailsService,解耦认证与用户信息获取。
Authorization
核心:AccessDecisionManager、AccessDecisionVoter
SecurityContext
核心:SecurityContextHolder、SecurityContext
安全内容,绑定到线程。
FilterChain
责任链模式;FilterChain–DelegatingFilterProxy/FilterChainProxy/FilterChain、Filter
SecurityContextPersistenceFilter;
UsernamePasswordAuthenticationFilter;身份验证
AnonymousAuthenticationFilter;
ExceptionTranslationFilter;
FilterSecurityInterceptor;访问控制
tomcat FilterChain:ApplicationFilterChain,包含Filter(Filter、DelegatingFilterProxy)
DelegatingFilterProxy持有FilterChainProxy,FilterChainProxy持有多个FilterChain;通过url匹配,返回适合的FilterChain,最终逐一执行。
DelegatingFilterProxy模式,关联web.xml配置、spring bean。
HttpSecurity#addFilterAt();不覆盖原filter,并行判定

Spring Security OAuth2

验证过程类似cas。
概念:客户端、资源服务器、授权服务器、用户/浏览器
模式:授权码模式(授权码浏览器中转、token浏览器不可见)、客户端模式、密码模式、简化模式
步骤:配置资源服务器、配置授权服务器、配置spring security

30.4 Actuator Security

management.endpoints.web.explosure.include;开启actuator url

31 Working with SQL Database

31.1 Configure a DataSource

Embedded Database Support
springboot可自动配置H2、HSQL等内嵌数据库。导入对应包即可。

  • com.h2database@h2,H2数据库
  • org.hsqldb@hsqldb,HSQL

导入数据:

  • spring.datasource.schema;结构
  • spring.datasource.data;数据

Connection to a Production Database
指定数据库连接池:spring.datasource.type;默认为自动发现。配置连接池bean后失效。
指定数据库连接池信息:spring.datasource.tomcat/dbcp/druid.*

31.2 Using JdbcTemplate

配置信息:spring.jdbc.template.*

31.3 JPA and Spring Data JPA

Map objects to relational databases.
spring-boot-starter-data-jpa,引入了hibernate、spring data jpa、spring orm。
spring.jpa.*,配置JPA
spring.jpa.properties.hibernate.*、spring.jpa.hibernate.*,配置hibernate
Entity Classes
@Entity、@EntityScan
@Id、@GeneratedValue、@Column、
Spring Data JPA Repositories
DSL方式命名方法。
@Query、@Modifying
Creating and Dropping JPA Databases
spring.jpa.hibernate.ddl-auto=create-drop;DDL mode
默认情况下,DDL在applicationContext启动后执行。修改:

  • spring.jpa.generate-ddl;自动配置时使用ddl-auto
  • spring.jpa.hibernate.ddl-auto

Open EntityManager in View
spring.jpa.open-in-view;启用open entitymanager in view 模式。

31.4 Spring Data JDBC

@EnableJdbcRepositories,配置JDBC

31.5 Using H2’s Web Console

spring.h2.*,配置H2

  • spring.h2.console.enabled;启用console,生产环境时设为false,禁用
  • spring.h2.console.path;配置console访问路径

31.6 Using JOOQ

JOOQ,Java Object Oriented Query;通过java代码构建sql

32 Working with NoSQL Technologies

自动配置:redis、MongoDB、Neo4j、elasticsearch、LDAP等。

32.1 Redis

Redis,key-value数据库;可持久化;单线程,多路复用。
springboot提供两种自动配置:Lettuce、Jedis。
spring-boot-starter-data-redis,自动配置redis,默认使用Lettuce client。
Connecting to Redis
spring.redis.*;配置redis
注入bean,可选RedisConnectionFactory、StringRedisTemplate、RedisTemplate
导入common-pool2时,获取到pooled connection factory

32.2 MongoDB

MongoDB,文档数据库,分布式文件存储;JSON结构;
spring-boot-starter-data-mongo;
Connecting to a MongoDB Database
spring.data.mongodb.*;配置
注入bean,MongoDbFactory、MongoTemplate。
Spring Data MongoDB Repositories
类似JPA,实现Repository,DSL命名方法;实体标记@Entity。
@EnableMongoRepositories,绑定repository
spring.data.mongodb.repositories.type;默认auto

32.3 Neo4j

Neo4j;graph数据库;点、边体系;
spring-boot-starter-data.neo4j
Connecting to a Neo4j Database
配置:spring.data.neo4j.*
注入bean,org.neo4j.ogm.session.Session
Using the Embedded Mode
导包:neo4j-ogm-embedded-driver
配置:spring.data.neo4j.embedded-enabled;默认true
Neo4jSession
spring.data.neo4j.open-in-view,开启open-in-view mode
Spring Data Neo4j Repositories
类同MongoDB。
@EnableNeo4jRepositories、spring.data.neo4j.repositories.enabled

32.6 Elasticsearch

elasticsearch;distributed、restful search and analysis engine。
spring-boot-starter-data-elasticsearch;
Connecting to Elasticsearch by REST Client
两种rest client,配置spring.elasticsearch.rest.*:

  • 导包:elasticsearch-rest-client;配置RestClient
  • 导包:elasticsearch-rest-high-level-client;配置RestHighLevelClient

Connecting to Elasticsearch by Using Jest
导入jest,配置JestClient;参数:spring.elasticsearch.jest.*
Connecting to Elasticsearch by Using Spring Data
spring.data.elasticsearch.*;配置连接信息
注入bean,ElasticsearchTemplate、TransportClient
Spring Data Elasticsearch Repositories
类同以上,实体类注解@Document
spring.data.elasticsearch.repositories.enabled;

32.9 LDAP

LDAP,Lightweight Directory Access Protocal;
spring-boot-starter-data-ldap
Connecting to an LDAP Server
spring.ldap.*;配置连接信息
注入bean,LdapTemplate
Spring Data LDAP Repositories
spring.data.ldap.repositories.enabled
Embedded In-memory LDAP
导包:unboundid-ldapsdk
配置:sping.ldap.embedded.base-dn: dc=spring,dc=io

33 Caching

结构:CacheProvider、CacheManager、Cache、Entry、Expiry
@EnableCaching,开启cache。cache-reuse,buffer-adapt
@CacheConfig、@Cacheable、@Caching、@CachePut、@CacheEvit
spring.cache.*
未导入cache相关包时,默认使用ConcurrentHashMap
spring-boot-starter-cache;导入cache基础支持

33.1 Supported Cache Providers

EhCache
导包:ehcache
配置:spring.cache.ehcache.config;配置文件位置,建议使用-spring后缀。
注入EhCacheManager bean,或基于注解使用
Redis
导包:jedis
配置:spring.cache.redis.*、spring.cache.cache-names;配置redis默认值、cache名
注入RedisCacheManager bean,或基于注解使用
如需定制序列化策略等,配置RedisCacheConfiguration bean。
redis数据结构:

  • string,字符串,字符数组实现,字符列表动态扩容
  • hash,拼接key实现?
  • list,字符串列表,按插入顺序排序
  • set,无序字符串集合,基于hash表实现;不允许重复
  • zset,有序字符串集合,同上,通过关联分数排序,分数可重

Simple
If no caching library is present,使用ConcurrentHashMap。
None
spring.cache.type=none;禁用缓存

34 Messaging

结构:ConnectionFactory、TransactionManager、Template、ListenerContainerFactory、MessageListener
Template自动关联MessageConverter bean

34.1 JMS

Java Message Service
配置:spring.jms.*
ActiveMQ Support
导包:spring-boot-starter-activemq
配置:spring.activemq.*
池化
By default,CachingConnectionFactory wrap native ConnectionFactory;配置spring.jms.cache.*
使用本地连接池,导入org.messaginghub@pool-jms;配置spring.activemq.pool
Sending a Message
注入JmsTemplate bean
Receiving a Message
@EnableJms,启用jms
@JmsListener,标记方法;ListenerContainerFactory、TransactionManager自动配置

34.2 AMQP

Advanced Message Queuing Protocol
导包:spring-boot-starter-amqp
RabbitMQ Support
配置:spring.rabbitmq.*
Sending a Message
注入bean,AmqpAdmin、AmqpTemplate
spring.rabbitmq.template.retry.*;无事务管理,retry默认false。自动关联MessageRecoverer
Receiving a Message
@EnableRabbit、@RabbitListener
配置retry,应对消息消费失败。

34.3 Apache Kafka

导包:spring-kafka
配置:spring.kafka.*
Sending a Message
注入bean KafkaTemplate
spring.kafka.producer.transaction-id-prefix;事务配置
Receiving a Message
@EnableKafka、@KafkaListener
Kafka Streams
流式计算。
导包:kafka-streams,@EnableKafkaStreams;
配置:spring.kafka.streams.*
注入bean StreamsBuilder,构建KStream bean。

35 Calling REST Services with RestTemplate

RestTemplateBuilder、RestTemplate、HttpMessageConverter
springboot自动配置RestTemplateBuilder。

35.1 RestTemplate Customization

实现RestTemplateCustomizer,配置为bean,应用到所有RestTemplate;如只应用到部分RestTemplate,new对象后作为RestTemplateBuilder方法参数。

37 Validation

@Validated,标记类
@Size、@NotNull、@Email等校验注解

38 Sending Email

结构:MailSender、MailMessage
导包:spring-boot-starter-mail
配置:spring.mail.*
注入bean JavaMailSender;MimeMessagePreparator、MimeMessageHelper构建MailMessage

39 Distributed Transactions with JTA

JTA环境被发现时,JMS、DataSource、JPA使用JtaTransactionManager管理事务。
spring.jta.enabled: false;禁用JTA
spring.jta.*

39.1 Using an Atomikos Transaction Manager

导包:spring-boot-starter-jta-atomikos
配置:spring.jta.atomikos.*
spring.jta.log-dir;日志路径,默认根路径
spring.jta.transaction-manager-id;默认为IP,unique ID

39.2 Using a Bitronix Transaction Manager

导包:spring-boot-starter-jta-bitronix
配置:spring.jta.bitronix.*
spring.jta.log-dir;日志路径,默认根路径
spring.jta.transaction-manager-id;默认为IP,unique ID

39.3 Using a Java EE Managed Transaction Manager

打war包,部署到容器中。
TransactionManager、JMS ConnectionFactory根据JNDI参数配置
DataSource可由spring.datasource.jndi-name配置

39.4 Mixing XA and Non-XA JMS Connection

注入non-XA ConnectionFactory;beanName nonXaJmsConnectionFactory
注入XA ConnectionFactory;by Type or by name “xaJmsConnectionFactory”

41 Quatz Scheduler

spring-boot-starter-quartz;配置spring.quatz.*
核心类:Scheduler、Trigger、Job/JobDetail;
SchedulerFactory绑定JobFactory,实现JobDetail自动装配。
SchedulerFactoryBeanCustomizer定制。
JobStore,默认为in-memory;配置为jdbc-based:

  • spring.quatz.jdbc.job-store-type: jdbc
  • spring.quatz.jdbc.initialize-schema: always 启动时初始化表结构
  • spring.quatz.jdbc.schema: fileName 自定义表结构,默认表结构为drop existing

@QuatzDataSource,标记quatz所用数据源

42 Task Execution and Scheduling

Task Execution
TaskExecutor、Task
springboot默认配置ThreadPoolTaskExecutor;支持异步task。
异步Task:@EnableAsync/@Async、异步请求;TaskExecutor自动执行。
配置:spring.task.execution.;TaskExecutorBuilder
Task Scheduling
TaskScheduler、策略、Task
springboot默认配置ThreadPoolTaskScheduler
定义Task:@EnableScheduling/@Scheduled、显式提交
配置:spring.task.scheduling.
;TaskSchedulerBuilder

43 Spring Integration

导包:spring-boot-starter-integration
开启:EnableIntegration
配置:spring.integration.*

44 Spring Session

管理用户session;存储位置:jdbc、redis、mongodb、hazelcast
Filter方式实现,包装request。redis示例:
导包:spring-session-data-redis
配置:

  • spring.session.store-type;存储位置,none禁用
  • spring.session.timeout;过期时间

45 Monitoring and Management over JMX

JMX:Java Management Extension
暴露bean:@ManagedResource、@ManagedAttribute、@ManagedOperation

49 Creating Your Own Auto-configuration

通过META-INF/spring.factories,加载bean;逗号隔开
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\classFullName
@Conditional注解族,条件性加载
@AutoConfigureAfter、@AutoConfigureBefore、@AutoConfigureOrder;加载顺序
@EnableConfigurationProperties;开启配置属性类
@Import;导入其他配置类
自动配置时,无法自动扫描;需手动配置关联。

Part V Spring Boot Actuator: Production-ready features

/actuator,获取信息;不同版本,信息不同

52 Enabling Production-ready Features

导包:spring-boot-starter-actuator

53 Endpoints

53.1 Enabling Endpoints
配置:management.endpoint.<ID>.enabled=true
management.endpoint.enabled-by-defualt=false;默认禁用,需手动逐一开启
53.2 Exposing Endpoints
web方式默认只暴露health、info
management.endpoints.jmx.exposure.include/exclude;配置JMX暴露项
management.endpoints.web.exposure.include/exclude;配置web暴露项
exclude优先;为所有项,yaml中加双引号""。
53.3 Securing HTTP Endpoints
spring security中,继承WebSecurityConfigurerAdapter,configure()方法中配置权限:
http.requestMatcher(EndpointRequest.toAnyReqeust()).authorizeRequest()
.anyRequest().hasRole(“ADMIN”)/permitAll();配置ADMIN角色/全部均可访问
开启endpoint:
management.endpoints.web.exposure.include/exclude
53.5 Hypermedia for Actuator Web Endpoints
/actuator;actuator总览页面
53.6 CORS Support
management.endpoints.web.cors.allow-origin/allow-method;配置cors origin/method
53.7 Implemention Custom Endponts
@Endpoint、@ReadOperation、@WriteOperation、@DeleteOperation;可通过jmx、http访问
@JmxEndpoint、@WebEndpoint;只能使用对应协议访问
53.8 Health Information
management.endpoints.health.*;配置health
自定义health信息,配置HealthIndicator bean。

54 Monitoring and Management over HTTP

54.1 Customizing the Management Endpoint Paths
management.endpoints.web.base-path;定制basePath,默认contextPath
54.2 Customizing the Management Server Port
management.server.port;定制端口,默认server.port
54.4 Customizing the Management Server Address
management.server.address;定制域名
54.5 Disabling HTTP Endpoints
management.server.port=0
management.endpoints.web.exposure.exclude=*

56 Loggers

TRACE、DEBUG、INFO、WARN、ERROR、FATAL、OFF、null
56.1 Configure a Logger
获取日志级别:get–http://ip:port/loggers
设置日志级别:post–http://ip:port/loggers/loggerName,entity:{‘configuredLevel’:‘LEVEL’}

结构

SpringApplication;定制、事件、runner
Environment;properties、profile配置
日志;JCL、SLF4j
MVC;mvc配置、容器配置、JSON/GSON、session管理
安全;spring security
数据;sql/事务、nosql、cache
消息;jms、amqp、kafka
整合;REST、验证、Email、Task(Executor、Scheduler/Quartz)
监控;http/SpringAdmin、jmx/jconsole

《SpringBoot官方文档》_笔记相关推荐

  1. ZooKeeper官方文档学习笔记03-程序员指南03

    我的每一篇这种正经文章,都是我努力克制玩心的成果,我可太难了,和自己做斗争. ZooKeeper官方文档学习笔记04-程序员指南03 绑定 Java绑定 客户端配置参数 C绑定 陷阱: 常见问题及故障 ...

  2. Javassist 官方文档 随手笔记

    Javassist 官方文档 随手笔记 Javassist.CtClass Class search path Introspection and customization \$0, \$1, \$ ...

  3. Open3D官方文档学习笔记

    Open3D官方文档学习笔记 第一部分--点云 1 可视化点云 2 体素降采样 3 顶点法线评估 4 访问顶点法线 补充:Numpy在Open3D中的应用 5 裁剪点云 补充1:获取点云坐标 补充2: ...

  4. SpringBoot 官方文档

    一. 文档下载 1.SpringBoot官方文档下载地址 https://docs.spring.io/spring-boot/docs/current/reference/ 二. 文档解读 1. s ...

  5. tensorflow官方文档_开源分享:最好的TensorFlow入门教程

    如果一门技术的学习曲线过于陡峭,那么我们在入门时的场景往往是,一鼓作气,没入门,再而衰,三而竭.演绎一出从入门到放弃的败走麦城. 今天发现一个入门TensorFlow的宝藏,迫不及待的分享给大家.这个 ...

  6. vue.js 2.0 官方文档学习笔记 —— 01. vue 介绍

    这是我的vue.js 2.0的学习笔记,采取了将官方文档中的代码集中到一个文件的形式.目的是保存下来,方便自己查阅. !官方文档:https://cn.vuejs.org/v2/guide/ 01. ...

  7. dubbo官方文档_狂神说SpringBoot17:Dubbo和Zookeeper集成

    狂神说SpringBoot系列连载课程,通俗易懂,基于SpringBoot2.2.5版本,欢迎各位狂粉转发关注学习.未经作者授权,禁止转载 分布式理论 什么是分布式系统? 在<分布式系统原理与范 ...

  8. OpenCV-Python官方文档学习笔记(上)

    整理自OpenCV-Python官方文档 一. OpenCV-Python Tutorials 1 安装及验证 2 图片读写,展示 3 视频读写,展示 4 绘图功能(绘制几何形状:线.圆.椭圆.矩形. ...

  9. kafka官方文档学习笔记2--QuickStart

    下载kafka https://www.apache.org/dyn/closer.cgi?path=/kafka/1.0.0/kafka_2.11-1.0.0.tgz 解压安装包 > tar ...

最新文章

  1. 伍六七带你学算法 动态规划 ——不同路径
  2. 基于感知损失的实时风格迁移与超分辨率重建
  3. Origin如何绘制泡泡图?
  4. C#LeetCode刷题之#744-寻找比目标字母大的最小字母(Find Smallest Letter Greater Than Target)
  5. Installing OwnCloud 9 on Debian 8
  6. 速成pytorch学习——4天中阶API示范
  7. 解决 Manjaro 中 Linuxqq扫码登陆闪退问题
  8. ElasticSearch 安装与API的使用
  9. 软件项目启动ppt_一直在启动不可行的软件项目
  10. teamviewer 服务器系统,远程支持服务器搭建teamviewer
  11. contextcapture多区块点云_基于ContextCapture倾斜摄影三维建模及其精度分析
  12. html微博登录代码,微博第三方登陆js实现
  13. GitHub学生优惠:repl.it 使用--Python爬虫示例
  14. java计算机毕业设计网上拍卖系统源码+数据库+系统+lw文档+mybatis+运行部署
  15. 计算机处理io和cpu,虚拟化技术原理(CPU、内存、IO)
  16. IOS应用分发的三种方式
  17. VL53L0X+stm32激光测距
  18. BMZCTF WEB WEB_penetration
  19. ui设计教程分享:关于Logo设计要素
  20. jQuery绑定一次性事件和注销事件

热门文章

  1. linux平台下一个好用的并行压缩工具(cpu核数越多越快,比tar -j可以快很多倍)
  2. 五分钟理解什么是面向对象
  3. Open Policy Agent(OPA) rego使用
  4. java多线程之Single Threaded Execution模式
  5. 使用微软云服务器搭建Hadoop集群
  6. (转自)何新:谈“玄”(一)
  7. DNS服务器配置:DNS服务器配置:正反解析,主从服务器,子域授权,
  8. C++实现RS485通信
  9. python 文件路径找不到_python路径正确但找不到文件
  10. g2o学习记录(1)安装和运行其下面的unit_test项目