SpringBoot3.0精讲笔记

 时间来到2022-3-25,好久没上官网,springBoot竟然出到3.0 M1。我用的最多的版本是2.2.2

 

Spring Boot Reference Documentationicon-default.png?t=M276https://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 Documentationicon-default.png?t=M276https://docs.spring.io/spring-boot/docs/3.0.0-M2/maven-plugin/reference/htmlsingle/ 6.1.5. Starters

Table 1. Spring Boot application starters
NameDescription

spring-boot-starter

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

spring-boot-starter-amqp

Starter for using Spring AMQP and Rabbit MQ

spring-boot-starter-aop

Starter for aspect-oriented programming with Spring AOP and AspectJ

spring-boot-starter-artemis

Starter for JMS messaging using Apache Artemis

spring-boot-starter-batch

Starter for using Spring Batch

spring-boot-starter-cache

Starter for using Spring Framework’s caching support

spring-boot-starter-data-cassandra

Starter for using Cassandra distributed database and Spring Data Cassandra

spring-boot-starter-data-cassandra-reactive

Starter for using Cassandra distributed database and Spring Data Cassandra Reactive

spring-boot-starter-data-couchbase

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

spring-boot-starter-data-couchbase-reactive

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

spring-boot-starter-data-elasticsearch

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

spring-boot-starter-data-jdbc

Starter for using Spring Data JDBC

spring-boot-starter-data-jpa

Starter for using Spring Data JPA with Hibernate

spring-boot-starter-data-ldap

Starter for using Spring Data LDAP

spring-boot-starter-data-mongodb

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

spring-boot-starter-data-mongodb-reactive

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

spring-boot-starter-data-neo4j

Starter for using Neo4j graph database and Spring Data Neo4j

spring-boot-starter-data-r2dbc

Starter for using Spring Data R2DBC

spring-boot-starter-data-redis

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

spring-boot-starter-data-redis-reactive

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

spring-boot-starter-data-rest

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

spring-boot-starter-freemarker

Starter for building MVC web applications using FreeMarker views

spring-boot-starter-groovy-templates

Starter for building MVC web applications using Groovy Templates views

spring-boot-starter-hateoas

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

spring-boot-starter-integration

Starter for using Spring Integration

spring-boot-starter-jdbc

Starter for using JDBC with the HikariCP connection pool

spring-boot-starter-jooq

Starter for using jOOQ to access SQL databases with JDBC. An alternative to spring-boot-starter-data-jpa or spring-boot-starter-jdbc

spring-boot-starter-json

Starter for reading and writing json

spring-boot-starter-mail

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

spring-boot-starter-mustache

Starter for building web applications using Mustache views

spring-boot-starter-oauth2-client

Starter for using Spring Security’s OAuth2/OpenID Connect client features

spring-boot-starter-oauth2-resource-server

Starter for using Spring Security’s OAuth2 resource server features

spring-boot-starter-quartz

Starter for using the Quartz scheduler

spring-boot-starter-rsocket

Starter for building RSocket clients and servers

spring-boot-starter-security

Starter for using Spring Security

spring-boot-starter-test

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

spring-boot-starter-thymeleaf

Starter for building MVC web applications using Thymeleaf views

spring-boot-starter-validation

Starter for using Java Bean Validation with Hibernate Validator

spring-boot-starter-web

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

spring-boot-starter-web-services

Starter for using Spring Web Services

spring-boot-starter-webflux

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

spring-boot-starter-websocket

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

Table 2. Spring Boot production starters
NameDescription

spring-boot-starter-actuator

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

 

Table 3. Spring Boot technical starters
NameDescription

spring-boot-starter-jetty

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

spring-boot-starter-log4j2

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

spring-boot-starter-logging

Starter for logging using Logback. Default logging starter

spring-boot-starter-reactor-netty

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

spring-boot-starter-tomcat

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

spring-boot-starter-undertow

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

6.3. Configuration Classes:we generally recommend that your primary source be a single @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 Documentationicon-default.png?t=M276https://docs.spring.io/spring-boot/docs/3.0.0-M2/reference/htmlsingle/#using.devtools.livereload

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

 spring.devtools.add-properties to false in your application.properties.

NameDefault Value

server.error.include-binding-errors

always

server.error.include-message

always

server.error.include-stacktrace

always

server.servlet.jsp.init-parameters.development

true

server.servlet.session.persistent

true

spring.freemarker.cache

false

spring.groovy.template.cache

false

spring.h2.console.enabled

true

spring.mustache.cache

false

spring.mvc.log-resolved-exception

true

spring.reactor.debug

true

spring.template.provider.cache

false

spring.thymeleaf.cache

false

spring.web.resources.cache.period

0

spring.web.resources.chain.cache

false

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.

7. Core Features

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<String> 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)

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、核心特色:

  1. 1:SpringBootAppliction   自定义bannner ,K8s状态Application Availability State
    @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、任务执行和调度
    1.         
      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:

    2. @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<String> headers = this.template.getForEntity("https://myhost.example.com/example", String.class);
              assertThat(headers.getHeaders().getLocation()).hasHost("other.example.com");
          }
      
      }

      5、Web

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

东宇科技

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值