时间来到2022-3-25,好久没上官网,springBoot竟然出到3.0 M1。我用的最多的版本是2.2.2
Spring Boot Reference Documentationhttps://docs.spring.io/spring-boot/docs/3.0.0-M2/reference/htmlsingle以下内容均是归纳整理。截图出于上面的连接,
1、概览:第一步,升级旧版,开发,特色,web,数据,消息,IO,镜像,高级。
2、第一步:Getting Started
$ java -version
4.4.1. Creating the POM
mvn dependency:tree
@RestController
@EnableAutoConfiguration
public class MyApplication {
@RequestMapping("/")
String home() {
return "Hello World!";
}
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
mvn spring-boot:run
mvn package The file should be around 10 MB in size.
jar tvf target/myproject-0.0.1-SNAPSHOT.jar
$ java -jar target/myproject-0.0.1-SNAPSHOT.jar
Spring Boot Maven Plugin Documentationhttps://docs.spring.io/spring-boot/docs/3.0.0-M2/maven-plugin/reference/htmlsingle/ 6.1.5. Starters
Name | Description |
---|---|
|
Core starter, including auto-configuration support, logging and YAML |
|
Starter for using Spring AMQP and Rabbit MQ |
|
Starter for aspect-oriented programming with Spring AOP and AspectJ |
|
Starter for JMS messaging using Apache Artemis |
|
Starter for using Spring Batch |
|
Starter for using Spring Framework’s caching support |
|
Starter for using Cassandra distributed database and Spring Data Cassandra |
|
Starter for using Cassandra distributed database and Spring Data Cassandra Reactive |
|
Starter for using Couchbase document-oriented database and Spring Data Couchbase |
|
Starter for using Couchbase document-oriented database and Spring Data Couchbase Reactive |
|
Starter for using Elasticsearch search and analytics engine and Spring Data Elasticsearch |
|
Starter for using Spring Data JDBC |
|
Starter for using Spring Data JPA with Hibernate |
|
Starter for using Spring Data LDAP |
|
Starter for using MongoDB document-oriented database and Spring Data MongoDB |
|
Starter for using MongoDB document-oriented database and Spring Data MongoDB Reactive |
|
Starter for using Neo4j graph database and Spring Data Neo4j |
|
Starter for using Spring Data R2DBC |
|
Starter for using Redis key-value data store with Spring Data Redis and the Lettuce client |
|
Starter for using Redis key-value data store with Spring Data Redis reactive and the Lettuce client |
|
Starter for exposing Spring Data repositories over REST using Spring Data REST |
|
Starter for building MVC web applications using FreeMarker views |
|
Starter for building MVC web applications using Groovy Templates views |
|
Starter for building hypermedia-based RESTful web application with Spring MVC and Spring HATEOAS |
|
Starter for using Spring Integration |
|
Starter for using JDBC with the HikariCP connection pool |
|
Starter for using jOOQ to access SQL databases with JDBC. An alternative to spring-boot-starter-data-jpa or spring-boot-starter-jdbc |
|
Starter for reading and writing json |
|
Starter for using Java Mail and Spring Framework’s email sending support |
|
Starter for building web applications using Mustache views |
|
Starter for using Spring Security’s OAuth2/OpenID Connect client features |
|
Starter for using Spring Security’s OAuth2 resource server features |
|
Starter for using the Quartz scheduler |
|
Starter for building RSocket clients and servers |
|
Starter for using Spring Security |
|
Starter for testing Spring Boot applications with libraries including JUnit Jupiter, Hamcrest and Mockito |
|
Starter for building MVC web applications using Thymeleaf views |
|
Starter for using Java Bean Validation with Hibernate Validator |
|
Starter for building web, including RESTful, applications using Spring MVC. Uses Tomcat as the default embedded container |
|
Starter for using Spring Web Services |
|
Starter for building WebFlux applications using Spring Framework’s Reactive Web support |
|
Starter for building WebSocket applications using Spring Framework’s WebSocket support |
Name | Description |
---|---|
|
Starter for using Spring Boot’s Actuator which provides production ready features to help you monitor and manage your application |
Name | Description |
---|---|
|
Starter for using Jetty as the embedded servlet container. An alternative to spring-boot-starter-tomcat |
|
Starter for using Log4j2 for logging. An alternative to spring-boot-starter-logging |
|
Starter for logging using Logback. Default logging starter |
|
Starter for using Reactor Netty as the embedded reactive HTTP server. |
|
Starter for using Tomcat as the embedded servlet container. Default servlet container starter used by spring-boot-starter-web |
|
Starter for using Undertow as the embedded servlet container. An alternative to spring-boot-starter-tomcat |
6.2.2. Locating the Main Application Class:The @SpringBootApplication annotation is often placed on your main class
@Configuration
class. Usually the class that defines the main
method is a good candidate as the primary @Configuration
.6.5. Beans 和 依赖注入
We generally recommend using constructor injection to wire up dependencies and @ComponentScan to find beans. You can add @ComponentScan without any arguments or use the @SpringBootApplication annotation which implicitly includes it. All of your application components (@Component, @Service, @Repository, @Controller, and others) are automatically registered as Spring Beans.
6.6. Using the @SpringBootApplication Annotation :三个(@EnableAutoConfiguration,@ComponentScan,@SpringBootConfiguration)
6.7. Running Your Application
IDE:select Import…
→ Existing Maven Projects
from the File
menu Relaunch
button
PackagedApplication: $ java -jar target/myapplication-0.0.1-SNAPSHOT.jar
java -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=8000,suspend=n \ -jar target/myapplication-0.0.1-SNAPSHOT.jar
MavenPlugin: mvn spring-boot:run export MAVEN_OPTS=-Xmx1024m
HotSwapping:热重载
spring-boot-devtools, Devtools works by monitoring the classpath for changes.
Spring Boot Reference Documentationhttps://docs.spring.io/spring-boot/docs/3.0.0-M2/reference/htmlsingle/#using.devtools.livereload
org.springframework.boot
spring-boot-devtools
true
spring.devtools.add-properties
to false
in your application.properties
.
Name | Default Value |
---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
you can turn on the spring.mvc.log-request-details
or spring.codec.log-request-details
configuration properties.
spring.devtools.restart.exclude=static/**,public/**
System.setProperty("spring.devtools.restart.enabled", "false");
Executable jars can be used for production deployment.
banner.txt SpringApplication.setBanner(…)
method
Use the org.springframework.boot.Banner
interface
The printed banner is registered as a singleton bean under the following name: springBootBanner
.
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication application = new SpringApplication(MyApplication.class);
application.setBannerMode(Banner.Mode.OFF);
application.run(args);
}
}
new SpringApplicationBuilder()
.sources(Parent.class)
.child(Application.class)
.bannerMode(Banner.Mode.OFF)
.run(args);
Spring MVC AnnotationConfigServletWebServerApplicationContext is used
Spring WebFlux AnnotationConfigReactiveWebServerApplicationContext is used
Otherwise, AnnotationConfigApplicationContext is used
获取参数
@Component
public class MyBean {
public MyBean(ApplicationArguments args) {
boolean debug = args.containsOption("debug");
List files = args.getNonOptionArgs();
if (debug) {
System.out.println(files);
}
// if run with "--debug logfile.txt" prints ["logfile.txt"]
}
}
附加任务
@Component
public class MyCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) {
// Do something...
}
}
程序退出
@SpringBootApplication
public class MyApplication {
@Bean
public ExitCodeGenerator exitCodeGenerator() {
return () -> 42;
}
public static void main(String[] args) {
System.exit(SpringApplication.exit(SpringApplication.run(MyApplication.class, args)));
}
}
其他设置方法:
SpringApplication.setDefaultProperties
@PropertySource annotations on your @Configuration
classes
Config data (such as application.properties
files)
A RandomValuePropertySource
that has properties only in random.*
@Component
public class MyBean {
@Value("${name}")
private String name;
// ...
}
for example, java -jar app.jar --name="Spring"
).
SpringApplication.setAddCommandLineProperties(false)
$ SPRING_APPLICATION_JSON='{"my":{"name":"test"}}' java -jar myapp.jar
$ java -Dspring.application.json='{"my":{"name":"test"}}' -jar myapp.jar
$ java -jar myapp.jar --spring.application.json='{"my":{"name":"test"}}'
加密属性
the Spring Cloud Vault project provides support for storing externalized configuration in HashiCorp Vault.
See Customize the Environment or ApplicationContext Before It Starts for details.
7.3 @Profile("production")
Any @Component
, @Configuration
or @ConfigurationProperties
can be marked with @Profile
to limit when it is loaded,
@Configuration(proxyBeanMethods = false)
@Profile("production")
public class ProductionConfiguration {
// ...
}
线程池
spring.task.execution.pool.max-size=16
spring.task.execution.pool.queue-capacity=100
spring.task.execution.pool.keep-alive=10s
8、Web
spring-boot-starter-web spring-boot-starter-webflux (
reactive web )
8.1 servlet-based web applications Spring MVC lets you create special @Controller
or @RestController
beans to handle incoming HTTP requests. Methods in your controller are mapped to HTTP by using @RequestMapping
annotations.
Spring MVC is part of the core Spring Framework,
@Configuration(proxyBeanMethods = false)
public class MyCorsConfiguration {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**");
}
};
}
}
9 Data:
10 Messaging
11 IO 缓存 , 定时 任务 发邮件 校验,webServices 订阅,
12 docker
13 生产准备特色
spring-boot-starter-actuator
14 部署
15: Cli
16: Plug
17 How to Guides
1、概览: 属性绑定,热部署,源码导入,自动配置,数据源,mp,web组件,MVC,模版,redis,消息,docker,jenkins, SpringCloud.
2、比较权威的springBoot介绍:
3、环境要求:Spring Boot Reference Documentation
4、热部署:
ctrl+shift+alt+/ compaire.autoMake.
配置文件放置位置4个。 file./config > file. > config/ > ./
5、核心特色:
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
2、外部化配置
spring:
application:
name: "myapp"
config:
import: "optional:file:./dev.properties"
spring:
config:
import: "file:/etc/config/myconfig[.yaml]"
k8s:
etc/
config/
myapp/
username
password
app:
name: "MyApp"
description: "${app.name} is a Spring Boot application"
my:
secret: "${random.value}"
number: "${random.int}"
bignumber: "${random.long}"
uuid: "${random.uuid}"
number-less-than-ten: "${random.int(10)}"
number-in-range: "${random.int[1024,65536]}"
3、@Profile("production")
4、任务执行和调度spring:
task:
execution:
pool:
max-size: 16
queue-capacity: 100
keep-alive: "10s"
spring:
task:
scheduling:
thread-name-prefix: "scheduling-"
pool:
size: 2
5、Test:
@SpringBootTest
@AutoConfigureMockMvc
class MyMockMvcTests {
@Test
void testWithMockMvc(@Autowired MockMvc mvc) throws Exception {
mvc.perform(get("/")).andExpect(status().isOk()).andExpect(content().string("Hello World"));
}
// If Spring WebFlux is on the classpath, you can drive MVC tests with a WebTestClient
@Test
void testWithWebTestClient(@Autowired WebTestClient webClient) {
webClient
.get().uri("/")
.exchange()
.expectStatus().isOk()
.expectBody(String.class).isEqualTo("Hello World");
}
}
class MyTests {
private TestRestTemplate template = new TestRestTemplate();
@Test
void testRequest() throws Exception {
ResponseEntity headers = this.template.getForEntity("https://myhost.example.com/example", String.class);
assertThat(headers.getHeaders().getLocation()).hasHost("other.example.com");
}
}
5、Web