SpringBoot官方笔记3核心

这篇具有很好参考价值的文章主要介绍了SpringBoot官方笔记3核心。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

SpringApplication

By default, INFO logging messages are shown, including some relevant startup details, such as the user that launched the application.

Lazy Initialization

When lazy initialization is enabled, beans are created as they are needed rather than during application startup.

spring.main.lazy-initialization=true

@Lazy(false) annotation:disable lazy initialization for certain beans

Customizing the Banner

adding a banner.txt file to your classpath or by setting the spring.banner.location property to the location of such a file. If the file has an encoding other than UTF-8, you can set spring.banner.charset.

SpringApplication.setBanner(…​) method

spring.main.banner-mode property System.out(console)、logger (log)、not produced at all (off)

The printed banner is registered as a singleton bean under the following name: springBootBanner.

Customizing SpringApplication

import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MyApplication {

    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(MyApplication.class);
        application.setBannerMode(Banner.Mode.OFF);
        application.run(args);
    }

}

The internal state of Spring Boot applications is mostly represented by the Spring ApplicationContext.

Internally, Spring Boot uses events to handle a variety of tasks. Application events are sent in the following order, as your application runs:

  1. An ApplicationStartingEvent is sent at the start of a run but before any processing, except for the registration of listeners and initializers.

  2. An ApplicationEnvironmentPreparedEvent is sent when the Environment to be used in the context is known but before the context is created.

  3. An ApplicationContextInitializedEvent is sent when the ApplicationContext is prepared and ApplicationContextInitializers have been called but before any bean definitions are loaded.

  4. An ApplicationPreparedEvent is sent just before the refresh is started but after bean definitions have been loaded.

  5. An ApplicationStartedEvent is sent after the context has been refreshed but before any application and command-line runners have been called.

  6. An AvailabilityChangeEvent is sent right after with LivenessState.CORRECT to indicate that the application is considered as live.

  7. An ApplicationReadyEvent is sent after any application and command-line runners have been called.

  8. An AvailabilityChangeEvent is sent right after with ReadinessState.ACCEPTING_TRAFFIC to indicate that the application is ready to service requests.

  9. An ApplicationFailedEvent is sent if there is an exception on startup.

Accessing Application Arguments

import java.util.List;

import org.springframework.boot.ApplicationArguments;
import org.springframework.stereotype.Component;

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

}

If you need to run some specific code once the SpringApplication has started, you can implement the ApplicationRunner or CommandLineRunner interfaces.

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class MyCommandLineRunner implements CommandLineRunner {

    @Override
    public void run(String... args) {
        // Do something...
    }

}

Application Exit

Each SpringApplication registers a shutdown hook with the JVM to ensure that the ApplicationContext closes gracefully on exit.

Externalized Configuration

Sources are considered in the following order:

  1. Default properties (specified by setting SpringApplication.setDefaultProperties).

  2. @PropertySource annotations on your @Configuration classes. Please note that such property sources are not added to the Environment until the application context is being refreshed. This is too late to configure certain properties such as logging.* and spring.main.* which are read before refresh begins.

  3. Config data (such as application.properties files).

  4. RandomValuePropertySource that has properties only in random.*.

  5. OS environment variables.

  6. Java System properties (System.getProperties()).

  7. JNDI attributes from java:comp/env.

  8. ServletContext init parameters.

  9. ServletConfig init parameters.

  10. Properties from SPRING_APPLICATION_JSON (inline JSON embedded in an environment variable or system property).

  11. Command line arguments.

  12. properties attribute on your tests. Available on @SpringBootTest and the test annotations for testing a particular slice of your application.

  13. @DynamicPropertySource annotations in your tests.

  14. @TestPropertySource annotations on your tests.

  15. Devtools global settings properties in the $HOME/.config/spring-boot directory when devtools is active.

Config data files are considered in the following order:

  1. Application properties packaged inside your jar (application.properties and YAML variants).

  2. Profile-specific application properties packaged inside your jar (application-{profile}.properties and YAML variants).

  3. Application properties outside of your packaged jar (application.properties and YAML variants).

  4. Profile-specific application properties outside of your packaged jar (application-{profile}.properties and YAML variants).

If you have configuration files with both .propertiesand YAML format in the same location, .properties takes precedence.

读取配置:

Property values can be injected directly into your beans by using the @Value annotation, accessed through Spring’s Environmentabstraction, or be bound to structured objects through @ConfigurationProperties.

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class MyBean {

    @Value("${name}")
    private String name;

    // ...

}

command line properties (that is, arguments starting with --, such as --server.port=9000) always take precedence over file-based property sources.

Spring Boot will automatically find and load application.properties and application.yaml files from the following locations when your application starts:

  1. From the classpath

    1. The classpath root

    2. The classpath /config package

  2. From the current directory

    1. The current directory

    2. The config/ subdirectory in the current directory

    3. Immediate child directories of the config/ subdirectory

Wildcard locations only work with external directories. You cannot use a wildcard in a classpath: location.

Profile Specific Files

application-{profile}. For example, if your application activates a profile named prod and uses YAML files, then both application.yaml and application-prod.yaml will be considered.

configtree:

etc/
  config/
    myapp/
      username
      password
spring.config.import=optional:configtree:/etc/config/

You can then access or inject myapp.username and myapp.password properties from the Environment in the usual way.

Property placeholders can also specify a default value using a : to separate the default value from the property name, for example ${name:default}.

app.name=MyApp
app.description=${app.name} is a Spring Boot application written by ${username:Unknown}

Working With YAML

If you use “Starters”, SnakeYAML is automatically provided by spring-boot-starter.

YAML files cannot be loaded by using the @PropertySource or @TestPropertySource annotations. So, in the case that you need to load values that way, you need to use a properties file.

The YamlPropertiesFactoryBeanloads YAML as Properties and the YamlMapFactoryBean loads YAML as a Map. YamlPropertySourceLoader class if you want to load YAML as a Spring PropertySource.

Configuring Random Values

RandomValuePropertySource

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

Type-safe Configuration Properties

@ConfigurationProperties

Relaxed Binding

As an example, consider the following @ConfigurationProperties class:

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "my.main-project.person")
public class MyPersonProperties {

    private String firstName;

    public String getFirstName() {
        return this.firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

}

With the preceding code, the following properties names can all be used:

  • my.main-project.person.first-name Kebab case, which is recommended for use in .properties and YAML files.

  • my.main-project.person.firstName Standard camel case syntax.

  • my.main-project.person.first_name Underscore notation, which is an alternative format for use in .properties and YAML files.

  • MY_MAINPROJECT_PERSON_FIRSTNAME Upper case format, which is recommended when using system environment variables.

We recommend that, when possible, properties are stored in lower-case kebab format, such as my.person.first-name=Rod.

Profiles

make it be available only in certain environments

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

@Configuration(proxyBeanMethods = false)
@Profile("production")
public class ProductionConfiguration {

    // ...

}

Logging

By default, if you use the “Starters”, Logback is used for logging.

Log Format

2023-06-22T12:08:05.861Z  INFO 22768 --- [           main] o.s.b.d.f.s.MyApplication                : Starting MyApplication using Java 17.0.7 with PID 22768 (/opt/apps/myapp.jar started by myuser in /opt/apps/)
2023-06-22T12:08:05.872Z  INFO 22768 --- [           main] o.s.b.d.f.s.MyApplication                : No active profile set, falling back to 1 default profile: "default"
2023-06-22T12:08:09.854Z  INFO 22768 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2023-06-22T12:08:09.892Z  INFO 22768 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2023-06-22T12:08:09.892Z  INFO 22768 --- [           main] o.apache.catalina.core.StandardEngine    : Starting Servlet engine: [Apache Tomcat/10.1.10]
2023-06-22T12:08:10.160Z  INFO 22768 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2023-06-22T12:08:10.162Z  INFO 22768 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 4038 ms
2023-06-22T12:08:11.512Z  INFO 22768 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2023-06-22T12:08:11.534Z  INFO 22768 --- [           main] o.s.b.d.f.s.MyApplication                : Started MyApplication in 7.251 seconds (process running for 8.584)
  • Date and Time: Millisecond precision and easily sortable.

  • Log Level: ERRORWARNINFODEBUG, or TRACE.

  • Process ID.

  • --- separator to distinguish the start of actual log messages.

  • Thread name: Enclosed in square brackets (may be truncated for console output).

  • Logger name: This is usually the source class name (often abbreviated).

  • The log message.

Internationalization

spring.messages.basename=messages,config.i18n.messages
spring.messages.fallback-to-system-locale=false

JSON

Jackson is the preferred and default library. Auto-configuration for Jackson is provided and Jackson is part of spring-boot-starter-json.

@JsonComponent Custom Serializers and Deserializers

import java.io.IOException;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import org.springframework.boot.jackson.JsonComponent;

@JsonComponent
public class MyJsonComponent {

    public static class Serializer extends JsonSerializer<MyObject> {

        @Override
        public void serialize(MyObject value, JsonGenerator jgen, SerializerProvider serializers) throws IOException {
            jgen.writeStartObject();
            jgen.writeStringField("name", value.getName());
            jgen.writeNumberField("age", value.getAge());
            jgen.writeEndObject();
        }

    }

    public static class Deserializer extends JsonDeserializer<MyObject> {

        @Override
        public MyObject deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException {
            ObjectCodec codec = jsonParser.getCodec();
            JsonNode tree = codec.readTree(jsonParser);
            String name = tree.get("name").textValue();
            int age = tree.get("age").intValue();
            return new MyObject(name, age);
        }

    }

}

Task Execution and Scheduling

In the absence of an Executor bean in the context, Spring Boot auto-configures a ThreadPoolTaskExecutor with sensible defaults that can be automatically associated to asynchronous task execution (@EnableAsync) and Spring MVC asynchronous request processing.

ThreadPoolTaskScheduler can also be auto-configured if need to be associated to scheduled task execution (using @EnableScheduling for instance).

Testing

Most developers use the spring-boot-starter-test “Starter”, which imports both Spring Boot test modules as well as JUnit Jupiter, AssertJ, Hamcrest, and a number of other useful libraries.

  • JUnit 5: The de-facto standard for unit testing Java applications.

  • Spring Test & Spring Boot Test: Utilities and integration test support for Spring Boot applications.

  • AssertJ: A fluent assertion library.

  • Hamcrest: A library of matcher objects (also known as constraints or predicates).

  • Mockito: A Java mocking framework.

  • JSONassert: An assertion library for JSON.

  • JsonPath: XPath for JSON.

One of the major advantages of dependency injection is that it should make your code easier to unit test. You can instantiate objects by using the new operator without even involving Spring. You can also use mock objects instead of real dependencies.

By default, @SpringBootTest will not start a server. You can use the webEnvironment attribute of @SpringBootTest to further refine how your tests run:

  • MOCK(Default) : Loads a web ApplicationContext and provides a mock web environment. Embedded servers are not started when using this annotation. If a web environment is not available on your classpath, this mode transparently falls back to creating a regular non-web ApplicationContext. It can be used in conjunction with @AutoConfigureMockMvc or @AutoConfigureWebTestClient for mock-based testing of your web application.

  • RANDOM_PORT: Loads a WebServerApplicationContext and provides a real web environment. Embedded servers are started and listen on a random port.

  • DEFINED_PORT: Loads a WebServerApplicationContext and provides a real web environment. Embedded servers are started and listen on a defined port (from your application.properties) or on the default port of 8080.

  • NONE: Loads an ApplicationContext by using SpringApplication but does not provide any web environment (mock or otherwise).

Docker Compose Support

compose.yml file is typically created next to your application which defines and configures service containers.

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

Creating Your Own Auto-configuration

Classes that implement auto-configuration are annotated with @AutoConfiguration.

SSL

spring.ssl.bundle.jks.mybundle.key.alias=application
spring.ssl.bundle.jks.mybundle.keystore.location=classpath:application.p12
spring.ssl.bundle.jks.mybundle.keystore.password=secret
spring.ssl.bundle.jks.mybundle.keystore.type=PKCS12

参考资料:

https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#features文章来源地址https://www.toymoban.com/news/detail-588231.html

到了这里,关于SpringBoot官方笔记3核心的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • SpringBoot + Vue前后端分离项目实战 || 二:Spring Boot后端与数据库连接

    系列文章: SpringBoot + Vue前后端分离项目实战 || 一:Vue前端设计 SpringBoot + Vue前后端分离项目实战 || 二:Spring Boot后端与数据库连接 SpringBoot + Vue前后端分离项目实战 || 三:Spring Boot后端与Vue前端连接 SpringBoot + Vue前后端分离项目实战 || 四:用户管理功能实现 SpringBoot + Vue前后

    2024年02月11日
    浏览(50)
  • 微信小程序的授权登录-Java 后端 (Spring boot)

    微信开发文档链接:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/login.html 一个可以测试的微信小程序 此微信小程序的APPID和APPscret(至开发者后台获取) 从时序图我们可以了解到流程大致分为两步: 小程序端获取code后传给Java后台 Java后台获取code后向微信后台接口

    2024年02月09日
    浏览(38)
  • “从零开始学习Spring Boot:快速搭建Java后端开发环境“

    标题:从零开始学习Spring Boot:快速搭建Java后端开发环境 摘要:本文将介绍如何从零开始学习Spring Boot,并详细讲解如何快速搭建Java后端开发环境。通过本文的指导,您将能够快速搭建一个基于Spring Boot的Java后端开发环境并开始编写代码。 正文: 一、准备工作 在开始之前,

    2024年02月15日
    浏览(42)
  • 【springboot】Spring 官方抛弃了 Java 8!新idea如何创建java8项目

    我本来以为是 IDEA 版本更新导致的 Bug,开始还没在意。 直到我今天自己初始化项目时才发现:卧槽,Java 8 真没了?! 具体一点,应该是使用 IDEA 内置的 Spring Initializr 创建 Spring Boot 新项目时,没有 Java 8 的选项了,只剩下了 = 17 的版本 去网上搜了一圈,原来这是因为 Sprin

    2024年02月04日
    浏览(34)
  • 【Java核心知识】spring boot整合Mybatis plus + Phoenix 访问Hbase与使用注意

    为什么Phoenix能让开发者通过SQL访问Hbase而不必使用原生的方式?引用Phoenix官网上的一句话:SQL is just a way of expressing what you want to get not how you want to get it . 即SQL不是一种数据操作技术,而是一种特殊的表达方式。只是表示你需要什么而不是你如何获得。 一个集成了Phoenix的Hb

    2024年02月15日
    浏览(37)
  • 2023 最新版IntelliJ IDEA 2023.1创建Java Web前(vue3)后端(spring-boot3)分离 项目详细步骤(图文详解)

    2023 最新版IntelliJ IDEA 2023.1创建Java Web 项目详细步骤(图文详解) 本篇使用当前Java Web开发主流的spring-boot3框架来创建一个Java前后端分离的项目,前端使用的也是目前前端主流的vue3进行一个简单的项目搭建,让你距离Java全栈开发更近一步 🏴‍☠️。 使用版本: “17.0.1”

    2024年02月12日
    浏览(76)
  • 【官方中文文档】Mybatis-Spring #搭配 Spring Boot

    请查看 MyBatis Spring-boot-starter 子项目获取更多信息。

    2024年02月11日
    浏览(30)
  • Spring 官方建议的在 Spring Boot 应用中如何做单元测试

    Spring Boot 提供了丰富的测试功能,主要由以下两个模块组成: ● spring-boot-test:提供测试核心功能。 ● spring-boot-test-autoconfigure:提供对测试的自动配置。 Spring Boot 提供了一个 spring-boot-starter-test一站式启动器,如以下依赖配置所示。 测试启动器依赖不仅包含以上两个 Spring

    2024年02月08日
    浏览(36)
  • Spring Boot 整合 Shiro(后端)

    1 Shiro 什么是 Shiro 官网: http://shiro.apache.org/ 是一款主流的 Java 安全框架,不依赖任何容器,可以运行在 Java SE 和 Java EE 项目中,它的主要作用是对访问系统的用户进行身份认证、 授权、会话管理、加密等操作。 Shiro 就是用来解决安全管理的系统化框架。 2 Shiro 核心组件 用

    2024年02月09日
    浏览(41)
  • 5.0 Spring Boot核心

    注解名称 注解说明 @SpringBootApplication 用于标注Spring Boot应用为启动类,是一个组合注解,主要组合了@SpringBootConfiguration、@EnableAutoConfiguration和@ComponentScan注解 @SpringBootConfiguration 继承自@Configuration,标注当前类是配置类 @EnableAutoConfiguration 开启自动装配 @ComponentScan 启动组件扫描

    2024年02月12日
    浏览(21)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包