此文章为Spring Boot Reference Guide(2.1.5.RELEASE)的备忘录。

Chapter 8. Introducing Spring Boot

You can use Spring Boot to create a Java application that can be started by using java -jar or more traditional war deployments.

Spring Boot 2.1.5.RELEASE requires:

  1. Java 8 and is compatible up to Java 11(included).
  2. Spring Framework 5.1.6.RELEASE or above
  3. Maven 3.3 or above

Chapter 10. Installing Spring Boot

Installation Instruction for the Java Developer (Ways)

  1. Including the appropriate spring-boot-*.jar files on your classpath in the same way as any standard Java library.
  2. Install appropriate Maven, make POM file inheriting from the spring-boot-starter-patent project and declare dependence spring-boot-starter-web. Optionally config Maven plugin to package the project as an executable jar file.
<?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 https://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.5.RELEASE</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>

</project>
DEPENDENCIES AUTO UPGRATED
SPRING-BOOT-START-PARENT 1

The spring-boot-start-parent provides a dependency-management section so that we can omit version tags for "blessed" dependences. When you upgrade Spring Boot itself, these dependencies are upgraded as well in a consistent way.
With this setup, we can also override individual dependencies by configure as below

<properties>
    <spring-data-releasetrain.version>Fowler-SR2</spring-data-releasetrain.version>
</properties>
  1. Install the Spring Boot CLI and run spring run app.groovy.
@RestController
class ThisWillActuallyRun {

    @RequestMapping("/")
    String home() {
        "Hello World!"
    }

}
  1. Generate a new project structure by going to https://start.spring.io to shortcut steps.
  2. Using scope=import dependencies as follows to keep the benefit of the dependency management(but not th e plugin management) and override individual dependencies.
<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>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>2.1.5.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
Upgrading from an Early Version of Spring Boot, you may need spring-boot-properties-migrator

Chapter 11. Developing First Spring Boot Application

  1. Create a Maven pom.xml file and complete it, then run mvn package to test the working build.
mvn dependency:tree
  1. src/main/java/Example.java
import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.web.bind.annotation.*;

@RestController
@EnableAutoConfiguration    // Tell Spring Boot to "guess" how you want to configure Spring based on the jar dependences.
public class Example {

    @RequestMapping("/")
    String home() {
        return "Hello World!";
    }

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

}
  1. Run mvn spring-boot:run to start the application.
  2. Add the spring-boot-maven-plugin to out pom.xml to used to create an executable jar.
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
MAMUAL OPERATIION REQUIRED
SPRING-BOOT-START-PARENT 2

the spring-boot-starter-parent POM includes <executions> configuration to bind the package goal. if you do not use the parent POM, you need to declare this configuration yourself. See https://docs.spring.io/spring-boot/docs/2.1.5.RELEASE/maven-plugin/usage.html for more detail.

  1. run mvn package to create an executable jar.
  2. run jave -jar target/myproject-0.0.1-SNAPSHOT.jar to launch the application.
You can use jar -tvf to peek inside.
EXAMPLES

some samples can be referenced at https://github.com/spring-projects/spring-boot/tree/v2.1.5.RELEASE/spring-boot-samples

DEPENDENCIES LIST

All the spring modules that can use with Spring Boot, as well as refined third part libraries, can be found at https://github.com/spring-projects/spring-boot/blob/v2.1.5.RELEASE/spring-boot-project/spring-boot-dependencies/pom.xml

Chapter 13. Structuring Code

Location of Mail Application Class

The @SpringBootApplication annotation is often placed on the main classpath, and it implicitly defines as base "search package" for certain items. Using a root package also allows the component scan to apply only on this project.

SpringBootApplication

@SpringBootApplication == @EnableAutoConfiguration + @ComponentScan + @Configuration

Typical Layout:

com
 +- example
     +- myapplication
         +- Application.java
         |
         +- customer
         |   +- Customer.java
         |   +- CustomerController.java
         |   +- CustomerService.java
         |   +- CustomerRepository.java
         |
         +- order
             +- Order.java
             +- OrderController.java
             +- OrderService.java
             +- OrderRepository.java

Chapter 15. Configuration Class

  • We generally recommend that the primary source be a single @Configuration class. Usually, the main class is a good candidate as the primary *@Configurations
  • @Import can be used to import additional configuration classes.
  • Alternatively, @ComponentScan can be used to automatically pick up all Spring component including @Configuration classes.
  • @ImportResource can be used to import load XML configurations file(Totally not recommended)

Chapter 16. Auto-configuration

@EnableAutoConfiguration or @SpringBootApplication attempts to automatically configure application based on the jar dependencies. we generally recommend that you add one or the other to your primary @Configuration class only.

--DEBUG SWITCH WHEN START

  1. To find out what auto-configuration is currently being applied.

We can define exclusion both at the annotation level and ny using the property.

Chapter 17. Spring Beans and Dependency Injection

@ComponentsScan in maim class will automatically register @Component, @Service, @Repository, @Controller etc. as Spring Beans

Chapter 20. Developer Tools

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

Property Default

Developer tools are automatically disabled when running a fully packages. Applications launched from java -jar or started from a special class loader are considered as fully packages.
If that does not apply to you, try to exclude devtools or set the -Dspring.devtools.restart.enabled=false system property.

devtool properties

Automatic Restart

DevTools relies on the application context’s shutdown hook to close it during a restart. It does not work correctly if you have disabled the shutdown hook (SpringApplication.setRegisterShutdownHook(false)).

RESTART TECHNOLOGY
Two class loader, base and restart. Classes that do not change(for example third part jar) are loaded into base. Classes that are under development are loaded into restart. When restart, throw restart away. Take advantages of already available and populated base class loader.
Generally speaking, any project in IDE is loaded with the restart and any regular .jar file is loaded with base.

spring.devtools.restart.log-condition-evaluation-delta=false

Disable the logging of the report that shows the condition evaluation delta when restart triggered.

spring.devtools.restart.exclude=static/,public/
spring.devtools.restart.additional-exclude
spring.devtools.restart.additional-paths
spring.devtools.restart.enabled(when false, restart class loader still be initiated but does not watch for file change)
(System property)spring.devtools.restart.enabled(completely disable)

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

spring.devtools.restart.trigger-file
spring.devtools.livereload.enabled

LIVE RELOAD

trigger browser refresh when a resource is changed.[http://livereload.com/extensi...]

Global Settings

Remote Application

Can be used in development environment.

Chapter 23 SpringApplication

FailureAnalyzers to handle error occur when failed to start.
If no analyzer was matched, you can use DEBUG mode when launching application to see detail info.

Customizing the Banner

  1. Adding a banner.txt file to class path.
  2. Setting spring.banner.location property to locate an other file(spring.banner.charset).
  3. Add banner.gif .pnf .jpg to class path.
  4. Setting spring.banner.image.location
  5. SpringApplication.setBanner, .org.springFramework.boot.banner interface and printBanner method.

Placeholders can be used.
MANIFEST.MF
spring.main.banner-mode: console, log, off

Customizing SpringApplication

Fluent Builder API

https://docs.spring.io/spring-boot/docs/2.1.5.RELEASE/api/org/springframework/boot/builder/SpringApplicationBuilder.html

Application Events and Listeners

You often need not use application events, bunt it is handy to know that they exist.

Web Environment

Determine WebApplicationType:

  1. If Spring MVC is present, an AnnotationConfigServletWebServerApplicationContext is used
  2. If Spring MVC is not present and Spring WebFlux is present, an AnnotationConfigReactiveWebServerApplicationContext is used
  3. Otherwise, AnnotationConfigApplicationContext is used

Changed by setWebApplicationType(WebApplicationType). setApplicationContextClass(…​).

Accessing Application Arguments

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

}

Or can be used by @Value annotation

Using Application Runner or CommandLineRunner

Used when you want to run some special code once the SpringApplication has started.

Application Exit

Admin Features

Chapter 24 Externalized Configuration

Override order

  • ~/.spring-boot-devtools.properties
  • Command line arguments. java -jar app.jar —ame=“Spring”. disabled by: SpringApplication.setAddCommandLineProperties(false)
  • SPRING_APPLICATION_JSON.

    • $ SPRING_APPLICATION_JSON='{"acme":{"name":"test"}}' && java -jar myapp.jar
    • java -Dspring.application.json='{"name":"test"}' -jar myapp.jar
    • java -jar myapp.jar --spring.application.json='{"name":"test"}
  • Java system properties
  • OS environment variables
  • application.properties

    • Name and path can be changed:

      • java -jar myproject.jar --spring.config.name=myproject.
      • java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties
  • Search order by default:

    1. file:./config/
    2. file:./
    3. classpath:/config/
    4. classpath:/

Usage: @Value("${name}")

Random Value

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

Profile-specific Properties

Placeholder in Properties

app.name=MyApp
app.description=${app.name} is a Spring Boot application
// system properties and else

Type-safe Configuration Properties

Spring boot provides an alternative method of working with properties that lets strongly typed bean govern and validate the configuration of application.

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

    }
}

@Component
@ConfigurationProperties(prefix="acme")
public class AcmeProperties {

    // ... see the preceding example

}

# application.yml

acme:
    remote-address: 192.168.1.1
    security:
        username: admin
        roles:
          - USER
          - ADMIN

@Service
public class MyService {

    private final AcmeProperties properties;

    @Autowired
    public MyService(AcmeProperties properties) {
        this.properties = properties;
    }

     //...

    @PostConstruct
    public void openConnection() {
        Server server = new Server(this.properties.getRemoteAddress());
        // ...
    }
}

// Particularly useful when you want bind properties to third part components.
@ConfigurationProperties(prefix = "another")
@Bean
public AnotherComponent anotherComponent() {
    ...
}

Relaxed Binding

Merging

For all property scoures, both comma-separated lists and YAML lists can be used for completed overriding the contents of the list.

@ConfigurationProperties Validation

Chapter 25 Profile

Spring Profiles(@Profile) provide a way to segregate the @Component or @Configuration in your application and make it available only in certain environments.

CONFIGURATION
spring.profiles.active

Chapter26 Logging

Default configurations are provided for Java Util, Logging, Log4j using Commons Logging.

Starting application with a —debug or —tracer flag or set debug=true in application.properties to start corresponding mode.

spring.output.ansi.enable: enable color-code output used with %clr.
logging.file
logging.file.max-size
logging.file.max-history
logging.path

logging.level.<logger-name/group-name>=<level>
logging.level.root=WARN
logging.level.org.springframework.web=DEBUG
logging.level.org.hibernate=ERROR

logging.group.tomcat=org.apache.catalina, org.apache.coyote, org.apache.t

Log Groups

Group related logger together to configured then together.

Predefined log group:
org.springframework.core.codec, org.springframework.http, org.springframework.web

sql

org.springframework.jdbc.core, org.hibernate.SQL

Logging system configuration files

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

Using -spring variants are recommended.

More references can be found by searching.

Chapter 27 Internationalization

messages.properties

Chapter 28 JSON

Jackson is the preferred and default library.

Chapter 29 Developing Web Applications

The “Spring Web MVC Framework”

@RestController = @Controller + @ResponseBody

Spring MVC Auto-Configuration

Feature list that were added by Spring MVC.
And configure Spring MVC

Spring MVC uses the HttpMessageConverter to convert HTTP requests and responses and you can customize converter.

You can write your own JaonSerializer and JsonDeserializer using @JsonComponent
. JsonObjectSerializer was provides by Spring Boot as an alternatives to standard Jsckson version.

Static Content

Spring Boot serve static content from directories called /static, /public, /resource, /META-INF/resource.
Handled by ResourceHttpRrquestHandler and can be overrode by overriding the addResourceHandler in WebMvcConfiguration.

Servlet way, you can customize config using spring.mvc.static-path-pattern, spring.resource.static-locations.

And cache-busting and version of resource controls.

_

Welcome Page

Error Handling

Spring HATEOAS

_

CORS support

  1. @CrossOrigin on controller method
@Configuration
public class MyConfiguration {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/api/**");
            }
        };
    }
}

The “Spring WebFlux Framework”

It does not require the Servlet API, is fully asynchronous and non/blocking.

To start, add spring-boot-starter-webflux module;
When both spring.boot.starter.web and spring.boot.starter.webflux are added, web have the precedence because most developer only use the reactive webClient.
SpringApplication.setWebApplicationType(WebApplicationType.REACTIVE). can change this behavior.

  1. annotation-based flavor:
@RestController
@RequestMapping("/users")
public class MyRestController {

    @GetMapping("/{user}")
    public Mono<User> getUser(@PathVariable Long user) {
        // ...
    }

    @GetMapping("/{user}/customers")
    public Flux<Customer> getUserCustomers(@PathVariable Long user) {
        // ...
    }

    @DeleteMapping("/{user}")
    public Mono<User> deleteUser(@PathVariable Long user) {
        // ...
    }
}
  1. functional flavor: separate the routing configuration from the handing of request.
@Configuration
public class RoutingConfiguration {

    @Bean
    public RouterFunction<ServerResponse> monoRouterFunction(UserHandler userHandler) {
        return route(GET("/{user}").and(accept(APPLICATION_JSON)), userHandler::getUser)
                .andRoute(GET("/{user}/customers").and(accept(APPLICATION_JSON)), userHandler::getUserCustomers)
                .andRoute(DELETE("/{user}").and(accept(APPLICATION_JSON)), userHandler::deleteUser);
    }

}

@Component
public class UserHandler {

    public Mono<ServerResponse> getUser(ServerRequest request) {
        // ...
    }

    public Mono<ServerResponse> getUserCustomers(ServerRequest request) {
        // ...
    }

    public Mono<ServerResponse> deleteUser(ServerRequest request) {
        // ...
    }
}

If you want to keep Spring Boot WebFlux features and you want to add additional WebFlux configuration, you can add your own @Configuration class of type WebFluxConfigurer but without @EnableWebFlux.

If you want to take complete control of Spring WebFlux, you can add your own @Configuration annotated with @EnableWebFlux.

HTTP Codecs with HttpMessageReaders and HttpMessageWriters

Spring WebFlux uses the HttpMessageReader and HttpMessageWriter interfaces to convert HTTP requests and request

Embedded Servlet Container Support

Tomcat, Jetty, Undertow

ServletRegistrationBean, FilterRegistrationBean, and ServletListenerRegistrationBean

Servlet Filter Order
OrderedCharacterEncodingFilter

Ordered.HIGHEST_PRECEDENCE

WebMvcMetricsFilter

Ordered.HIGHEST_PRECEDENCE + 1

ErrorPageFilter

Ordered.HIGHEST_PRECEDENCE + 1

HttpTraceFilter

Ordered.LOWEST_PRECEDENCE - 1

Servlet Context Initialization

There is a intentional design that container does not directly execute the Servlet 3.0+ javax.servlet.ServletContainerInitializer interface or Spring’s org.springframework.web.WebApplicationInitializer interface.

You can access ServletContext in onStartup method whose class implement org.springframework.boot.web.servlet.ServletContextInitializer.

@WebServlet, @WebFilter, and @WebListener can be enabled by using @ServletComponentScan.

The ServletWevServerApplicationContext

Spring Boot uses a different type of ApplicationContext for embedded servlet container support. The ServletWebServerApplicationContext is a special type of WebApplicationContext that bootstraps itself by searching for a single ServletWebServerFactory bean. Usually a TomcatServletWebServerFactory, JettyServletWebServerFactory, or UndertowServletWebServerFactory has been auto-configured.

Customizing Embedded Servlet Container

server.port
server.host
server.servlet.session.*
server.error.path
etc.

Server Properties

You can configure the embedded servlet programmatically by implementing WebServerFactoryCustomizer(TomcatServletWebServerFactory provides additional setters) and access ConfigurableServletWebServerFactory by Customize method.

import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.stereotype.Component;

@Component
public class CustomizationBean implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {

    @Override
    public void customize(ConfigurableServletWebServerFactory server) {
        server.setPort(9000);
    }

}


// Directly way:
@Bean
public ConfigurableServletWebServerFactory webServerFactory() {
    TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
    factory.setPort(9000);
    factory.setSessionTimeout(10, TimeUnit.MINUTES);
    factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/notfound.html"));
    return factory;
}

Embedded Reactive Server Support

Spring Boot includes support for the following embedded reactive web servers: Reactor Netty, Tomcat, Jetty, and Undertow.

And clients, ReactorResourceFactory, ReactorResourceFactory and else.

Chapter 30. Security

spring.security.user.name:
spring.security.user.password: change the info of default user in UserDetailService.

The basic features you get:

  1. A UserDetailService(ReactiveUserDetailService in case of a WebFlux application)
  2. Form-based logon or HTTP basic security.
  3. A DefaultAuthenticationEventPublisher for publishing authentication events.(you can customize it)
  4. SecurityAutoConfiguration: imports SpringBootWebSecurityConfiguration for web security.
  5. UserDetailServiceAutoConfiguration: configures authentication.
  6. WebSecurityConfigurationAdapter(a bean of type): to configure web application(e.g. overrode access rules, Spring Boot provides convenience methods that can be used to override access rules for actuator endpoints and static resources.).
  7. UserDetailsService, AuthenticationProvider, or AuthenticationManager(bean): configure UserDetailService.
  8. ReactiveSecrityAutoConfiguration: imports WebFluxSecurityConfiguration for web security with 2 and WebFilterChainProxy to replace 3 but access rule configured by SecurityWebFilterChain and ReactiveUserDetailsService or ReactiveAuthenticationManager to replace 4.
@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
    return http
        .authorizeExchange()
            .matchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
            .pathMatchers("/foo", "/bar")
                .authenticated().and()
            .formLogin().and()
        .build();
}

OAuth2

spring-security-oauth2-client
spring.security.oauth2.client.registration.my-client-1.client-id=abcd
spring.security.oauth2.client.registration.my-client-1.client-secret=password
spring.security.oauth2.client.registration.my-client-1.client-name=Client for user scope
spring.security.oauth2.client.registration.my-client-1.provider=my-oauth-provider
spring.security.oauth2.client.registration.my-client-1.scope=user
spring.security.oauth2.client.registration.my-client-1.redirect-uri-template=https://my-redirect-uri.com
spring.security.oauth2.client.registration.my-client-1.client-authentication-method=basic
spring.security.oauth2.client.registration.my-client-1.authorization-grant-type=authorization_code

// issuer-url
spring.security.oauth2.client.provider.oidc-provider.issuer-uri=https://dev-123456.oktapreview.com/oauth2/default/

// use provider
spring.security.oauth2.client.registration.my-client.client-id=abcd
spring.security.oauth2.client.registration.my-client.client-secret=password
spring.security.oauth2.client.registration.my-client.provider=google

spring.security.oauth2.client.registration.google.client-id=abcd
spring.security.oauth2.client.registration.google.client-secret=password

OAuth2LoginAuthenticationFilter only processes URLs matching /login/oauth2/code/*.
Customize the redirect-url:

public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            .oauth2Login()
                .redirectionEndpoint()
                    .baseUri("/custom-callback");
    }
}
spring-security-oauth2-resource-server
spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://example.com/oauth2/default/v1/keys
spring.security.oauth2.resourceserver.jwt.issuer-uri=https://dev-123456.oktapreview.com/oauth2/default/

Or you can define your own JwtDecoder bean for servlet applications or a ReactiveJwtDecoder for reactive applications.

spring-security-oauth2-autoconfigure
Set up a OAuth 2.0 authorization server.

Actuator Security

All actuator other than /health and /info are disable by default.
management.endpoints.web.exposure.include.

In Spring Boot environment, they are secured.

WebSecurityConfigurerAdapter will full control actuator access rules.

Chapter 31. Working With SQL databases.

Connection Pool(Pooling Datasource)

spring.datasource.generate-unique-name:
Generate databases for each context without reuse.

HikariCP
spring.boot.start.jdbc or spring.boot.start.data.jpa will automatically get a dependency to HikariCP a and it’s the first one to choose in choosing algorithm.

Meanwhile, you can bypass the algorithm by setting the first property of following list.

spring.datasource.type: specify the connection pool to use.
spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver: can be ignored since the value can be deduced from the url.
etc.

spring.datasource.hikari.*: implementation-specific settings.

JNDI
https://www.ibm.com/developerworks/cn/java/j-jndi/index.html

JPA and Spring Data JPA

  • Hibernate: One of the most popular JPA implementations.
  • Spring Data JPA: Makes it easy to implement JPA-based repositories.
  • Spring ORMs: Core ORM support from the Spring Framework.

A typically entity class

package com.example.myapp.domain;

import java.io.Serializable;
import javax.persistence.*;

@Entity
public class City implements Serializable {

    @Id
    @GeneratedValue
    private Long id;

    @Column(nullable = false)
    private String name;

    @Column(nullable = false)
    private String state;

    // ... additional members, often include @OneToMany mappings

    protected City() {
        // no-args constructor required by JPA spec
        // this one is protected since it shouldn't be used directly
    }

    public City(String name, String state) {
        this.name = name;
        this.state = state;
    }

    public String getName() {
        return this.name;
    }

    public String getState() {
        return this.state;
    }

    // ... etc

}

spring.data.jpa.repositories.bootstrap-mode: default, deferred, lazy.

Creating or Dropping JPA Databases

spring.jpa.hibernate.ddl-auto=create-drop: configure JPA properties

spring.jpa.properties.hibernate.globally_quoted_identifiers=true: configure hibernate native properties

spring.jpa.generate-dd: less fine-grained than hibernate don’t-auto

Open EntityManager in View

spring.jpa.open-in-view:

Using H2

[https://www.h2database.com/ht...]

JOOQ(Java Object Oriented Query)

generates Java code from your database and lets you build type-safe SQL queries through its fluent API.

Chapter 32. Working with NoSQL Technologies

To be added

Chapter 33. Caching

@EnableCaching: enable the caching support.

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

@Component
public class MathService {

    @Cacheable("piDecimals")
    public int computePiDecimal(int i) {
        // ...
    }

}

A simple provider(use concurrent maps in memory) will be set when not specific cache library was added.

spring.cache.type: force a particular cache provider.
spring.cache.cache-names=cache1,cache2
spring.cache.redis.time-to-live=600000

spring-boot-starter-cache
Bring in spring-context-support
@Bean
public CacheManagerCustomizer<ConcurrentMapCacheManager> cacheManagerCustomizer() {
    return new CacheManagerCustomizer<ConcurrentMapCacheManager>() {
        @Override
        public void customize(ConcurrentMapCacheManager cacheManager) {
            cacheManager.setAllowNullValues(false);
        }
    };
}

And you can update or evict data.

Some providers can be chose such as Generic, JCache, Redies, Simple, None

To be supplied

Chapter 34. Messaging

JMS

AMQP

RabbitMQ support

Apache Kafka Support

Chapter 35. Calling Rest Services With RestTemplate

A restTemplateBuilder was auto-configured. Spring boot does not provide a single restTemplate since it often need to be customized.

@Service
public class MyService {

    private final RestTemplate restTemplate;

    public MyService(RestTemplateBuilder restTemplateBuilder) {
        this.restTemplate = restTemplateBuilder.build();
    }

    public Details someRestCall(String name) {
        return this.restTemplate.getForObject("/{name}/details", Details.class, name);
        // or to add basic auth support
        // builder.basicAuthentication("user", "password").build().
    }
}

RestTemplate Customization

Ways: depending on how widely the customizing applied.

  1. “To make the scope of any customizations as narrow as possible, inject the auto-configured RestTemplateBuilder and then call its methods as required. Each method call returns a new RestTemplateBuilder instance, so the customizations only affect this use of the builder.”
  2. Application-wide. use RestTemplateCustomizer.
static class ProxyCustomizer implements RestTemplateCustomizer {

    @Override
    public void customize(RestTemplate restTemplate) {
        HttpHost proxy = new HttpHost("proxy.example.com");
        HttpClient httpClient = HttpClientBuilder.create()
                .setRoutePlanner(new DefaultProxyRoutePlanner(proxy) {

                    @Override
                    public HttpHost determineProxy(HttpHost target,
                            HttpRequest request, HttpContext context)
                            throws HttpException {
                        if (target.getHostName().equals("192.168.0.5")) {
                            return null;
                        }
                        return super.determineProxy(target, request, context);
                    }

                }).build();
        restTemplate.setRequestFactory(
                new HttpComponentsClientHttpRequestFactory(httpClient));
    }

}
// configure the use of a proxy for all hosts except 192.168.0.5
  1. Create your own RestTemplateBuilder(rarely used).

Chapter 36. Calling REST Service With WebClient

If you have Spring WebFlux on your class path, you can use this.

Chapter 37. Validation

Supported as long as a JSR-303 implementation(such as Hibernate validator) is on the class path.

@Service
@Validated // for their methods to be searched for inline constraint annotations.
public class MyBean {

    public Archive findByCodeAndAuthor(@Size(min = 8, max = 10) String code,
            Author author) {
        ...
    }
}

Chapter 38. Sending Email

A default JavaMailerSender is created when spring.mail.host and spring-boot-starter-mail are available.

spring.mail.host
spring.mail.properties.mail.smtp.connectiontimeout=5000
spring.mail.properties.mail.smtp.timeout=3000
spring.mail.properties.mail.smtp.writetimeout=5000

spring.mail.jndi-name=mail/Session

Chapter 39. Distributed Transactions with JTA

Using an Atomikos Transaction Manager

spring-boot-starter-jta-atomikos

spring.jta.log-dir
spring.jta.atomikos.properties: customize the Atomikos UserTransactionServiceImp.
spring.jta.transaction-manager-id

Using a Bitronix Transaction Manager

spring-boot-starter-jta-bitronix

spring.jta.bitronix.properties

Using a Java EE Managed Transaction Manager

Mixing XA and Non-XA JMS Connections

Supporting an Alternative Embedded Transaction Manager

Chapter 40. Hazelcast

[https://juejin.im/post/5bea40...]

Chapter 41. Quartz Scheduler

spring-boot-starter-quartz

A scheduler is auto-configured through the SchedulerFactoryBean.

spring.quartz.job-store-type=jdbc: not in-memory JobaStore.
spring.quartz.jdbc.initialize-schema=always: initialize store scheme on startup.
spring.quartz.jdbc.schema: provide a script to handle db on startup. by default, it will drop existing tables and delete all triggers on every restarts.
spring.quartz.overwrite-existing-jobs:

spring.quartz & spring.quartz.properties &
SchedulerFactoryBeanCustomizer

Chapter 42. Task Execution and Scheduling.

ThreadPoolTaskExecutor is auto-configured in the absence of an Executor bean be automatically associated to @EnableAsync.

AsyncTaskExecutor
TaskExecutorBuilder

spring.task.execution.pool.max-threads=16
spring.task.execution.pool.queue-capacity=100
spring.task.execution.pool.keep-alive=10s

ThreadPoolTaskScheduler
@EnableScheduling
spring.task.scheduling
TaskSchedulerBuilder

Chapter 43. Spring Integration

If spring-boot-starter-integration is included, @EnableIntegration can be used.

spring-integration-jmx: message processing statistics are published over JMX.
spring-integration-jdbc: spring.integration.jdbc.initialize-schema=always

Chapter 44. Spring Session

Chapter 45. Monitoring and Management over JMX

Chapter 46. Testing

spring-boot-test: contains core items.
spring-boot-test-autoconfigure: support auto-configuration.
spring-boot-test-start: imports both as well as a number of useful libraries as JUnit, AssertJ, Hamcrest.

JUnit 4: The de-facto standard for unit testing java application.
Spring Test & Spring Boot Test:
AssertJ: A fluent assertion library.
Hamcrest: A library of Mather object(constrains and predicates).
Mackito: Mocking framework.
JSONassertion: A assertion library for JSON.
JsonPath: XPath for JSON.

[To be continue]

Chapter 47. WebSockets

spring-boot-starter-websocket

Reactive web application required:

spring-boot-starter-webflux:

<dependency>
    <groupId>javax.websocket</groupId>
    <artifactId>javax.websocket-api</artifactId>
</dependency>

Chapter 48. Web Services

spring-boot-starter-webservices

Chapter 49. Creating Your Own Auto-configuration

@Configuration: auto-configuration implemented with.
@Conditional: constrain when the auto-configuration should apply.
@ConditionalOnClass: ensure that auto-configuration applies only when relevant classes are found.
@ConditionalOnMissingBean: supplies only when you have not declared your own @Configuration.

[https://github.com/spring-pro...]

META-INF/spring.factories: list your configuration classes as below.

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.mycorp.libx.autoconfigure.LibXAutoConfiguration,\
com.mycorp.libx.autoconfigure.LibXWebAutoConfiguration

Make sure that auto-configurations are never the target of component scanning. @Import I’d recommended to do something like component scanning.

@AutoConfigureAfter and @AutoConfigureBefore can be used to specify order.
@AutoConfigureOrder can be used to specify order when auto-configurations should not have any directly knowledge of each other.

Class Conditions

@ConditionalOnClass and @ConditionalOnMissingClass let @Configuration be included based on the absence or presence of specific classes.

@Bean with separate @Configuration:

@Configuration
// Some conditions
public class MyAutoConfiguration {

    // Auto-configured beans

    @Configuration
    @ConditionalOnClass(EmbeddedAcmeService.class)
    static class EmbeddedConfiguration {

        @Bean
        @ConditionalOnMissingBean
        public EmbeddedAcmeService embeddedAcmeService() { ... }

    }

}

Bean Conditions

@ConditionalOnBean and @ConditionalOnMissingBean annotations let a bean be included based on the presence or absence of specific beans.

The target type defaults to the return type of the method.

@Configuration
public class MyAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public MyService myService() { ... }

}
@ConditionalOnBean and @ConditionalOnMissingBean are guaranteed to load after use-defined beans have been added.

@ConditionalOnBean and @ConditionalOnMissingBean do not prevent @Configuration classes from being created. The only difference between using these conditions at the class level and marking each contained @Bean method with the annotation is that the former prevents registration of the @Configuration class as a bean if the condition does not match.

Property Conditions

Resource Conditions

Web Application Conditions

A web application is an application that uses a Spring WebApplicationContext, defines a session scope, or has a StandardServletEnvironment.

SpEL Expression Conditions

Testing Your Auto-configuration

Creating Your Own Starter

  1. Auto-configuration module: auto-configuration code.
  2. Starter module: dependency management.

Chapter 50. kotlin Support


Eriasuitor
21 声望1 粉丝