资讯专栏INFORMATION COLUMN

Spring Boot Reference Guide Memorandum

imccl / 2837人阅读

</>复制代码

  1. 此文章为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:

Java 8 and is compatible up to Java 11(included).

Spring Framework 5.1.6.RELEASE or above

Maven 3.3 or above

Chapter 10. Installing Spring Boot Installation Instruction for the Java Developer (Ways)

Including the appropriate spring-boot-*.jar files on your classpath in the same way as any standard Java library.

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.

</>复制代码

  1. 4.0.0
  2. com.example
  3. myproject
  4. 0.0.1-SNAPSHOT
  5. org.springframework.boot
  6. spring-boot-starter-parent
  7. 2.1.5.RELEASE
  8. org.springframework.boot
  9. spring-boot-starter-web
  10. org.springframework.boot
  11. spring-boot-maven-plugin

</>复制代码

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

</>复制代码

  1. Fowler-SR2

Install the Spring Boot CLI and run spring run app.groovy.

</>复制代码

  1. @RestController
  2. class ThisWillActuallyRun {
  3. @RequestMapping("/")
  4. String home() {
  5. "Hello World!"
  6. }
  7. }

Generate a new project structure by going to https://start.spring.io to shortcut steps.

Using scope=import dependencies as follows to keep the benefit of the dependency management(but not th e plugin management) and override individual dependencies.

</>复制代码

  1. org.springframework.data
  2. spring-data-releasetrain
  3. Fowler-SR2
  4. pom
  5. import
  6. org.springframework.boot
  7. spring-boot-dependencies
  8. 2.1.5.RELEASE
  9. pom
  10. import

</>复制代码

  1. Upgrading from an Early Version of Spring Boot, you may need spring-boot-properties-migrator
Chapter 11. Developing First Spring Boot Application

Create a Maven pom.xml file and complete it, then run mvn package to test the working build.

</>复制代码

  1. mvn dependency:tree

src/main/java/Example.java

</>复制代码

  1. import org.springframework.boot.*;
  2. import org.springframework.boot.autoconfigure.*;
  3. import org.springframework.web.bind.annotation.*;
  4. @RestController
  5. @EnableAutoConfiguration // Tell Spring Boot to "guess" how you want to configure Spring based on the jar dependences.
  6. public class Example {
  7. @RequestMapping("/")
  8. String home() {
  9. return "Hello World!";
  10. }
  11. public static void main(String[] args) {
  12. SpringApplication.run(Example.class, args);
  13. }
  14. }

Run mvn spring-boot:run to start the application.

Add the spring-boot-maven-plugin to out pom.xml to used to create an executable jar.

</>复制代码

  1. org.springframework.boot
  2. spring-boot-maven-plugin

</>复制代码

  1. MAMUAL OPERATIION REQUIRED
    SPRING-BOOT-START-PARENT 2

    the spring-boot-starter-parent POM includes 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.

run mvn package to create an executable jar.

run jave -jar target/myproject-0.0.1-SNAPSHOT.jar to launch the application.

</>复制代码

  1. You can use jar -tvf to peek inside.

</>复制代码

  1. EXAMPLES

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

</>复制代码

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

</>复制代码

  1. SpringBootApplication

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

Typical Layout:

</>复制代码

  1. com
  2. +- example
  3. +- myapplication
  4. +- Application.java
  5. |
  6. +- customer
  7. | +- Customer.java
  8. | +- CustomerController.java
  9. | +- CustomerService.java
  10. | +- CustomerRepository.java
  11. |
  12. +- order
  13. +- Order.java
  14. +- OrderController.java
  15. +- OrderService.java
  16. +- 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.

</>复制代码

  1. --DEBUG SWITCH WHEN START

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

</>复制代码

  1. org.springframework.boot
  2. spring-boot-devtools
  3. true
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.

</>复制代码

  1. 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)).

</>复制代码

  1. 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)

</>复制代码

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

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

</>复制代码

  1. LIVE RELOAD
  2. 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

Adding a banner.txt file to class path.

Setting spring.banner.location property to locate an other file(spring.banner.charset).

Add banner.gif .pnf .jpg to class path.

Setting spring.banner.image.location

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:

If Spring MVC is present, an AnnotationConfigServletWebServerApplicationContext is used

If Spring MVC is not present and Spring WebFlux is present, an AnnotationConfigReactiveWebServerApplicationContext is used

Otherwise, AnnotationConfigApplicationContext is used

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

Accessing Application Arguments

</>复制代码

  1. import org.springframework.boot.*;
  2. import org.springframework.beans.factory.annotation.*;
  3. import org.springframework.stereotype.*;
  4. @Component
  5. public class MyBean {
  6. @Autowired
  7. public MyBean(ApplicationArguments args) {
  8. boolean debug = args.containsOption("debug");
  9. List files = args.getNonOptionArgs();
  10. // if run with "--debug logfile.txt" debug=true, files=["logfile.txt"]
  11. }
  12. }

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:

file:./config/

file:./

classpath:/config/

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

[To Be Continued]

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/75138.html

相关文章

  • Spring Boot 学习资料收集

    摘要:系列文章更新计划列表主要对一些中常用的框架进行简单的介绍及快速上手,外加相关资料的收集更新列表会不定期的加入新的内容以进行扩充,如果你对此感兴趣可以站内联系我。 导读: 从第一次接触Spring Boot 至今已经有半年多了,在这期间也浏览了许多和Spring Boot 相关的书籍及文章,公司里面的许多项目也一直在使用Spring Boot。关于Spring Boot的一些看法:Spr...

    mmy123456 评论0 收藏0
  • 开发人员常用框架文档整理及中文翻译

    摘要:开发人员常用的框架文档及中文翻译,包含系列文档,日志,,,,数据库,,等最新官方文档以及对应的中文翻译。其它如果你有针对此网站好的建议或意见,也欢迎提更多的文档和更多的文档版本支持 开发人员常用的框架文档及中文翻译,包含 Spring 系列文档(Spring, Spring Boot, Spring Cloud, Spring Security, Spring Session),日志(...

    BingqiChen 评论0 收藏0
  • 开发人员常用框架文档整理及中文翻译

    摘要:开发人员常用的框架文档及中文翻译,包含系列文档,日志,,,,数据库,,等最新官方文档以及对应的中文翻译。其它如果你有针对此网站好的建议或意见,也欢迎提更多的文档和更多的文档版本支持 开发人员常用的框架文档及中文翻译,包含 Spring 系列文档(Spring, Spring Boot, Spring Cloud, Spring Security, Spring Session),日志(...

    objc94 评论0 收藏0
  • Spring Boot 2.0 外部化配置介绍

    摘要:可以使用外部化配置来方便在不同环境的运行同样的程序文件文件环境变量命令行参数内置顺序实现了很多按以下顺序进行合理的相同属性的覆盖目录下的全局设置属性,如果激活测试用例上的注解测试用例上的注解。 简介 在应用中管理配置并不是一个容易的任务,尤其是在应用需要部署到多个环境中时。通常会需要为每个环境提供一个对应的属性文件,用来配置各自的数据库连接信息、服务器信息和第三方服务账号等。通常的应用...

    lmxdawn 评论0 收藏0

发表评论

0条评论

imccl

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<