当前位置: 首页 > 工具软件 > Silence-Boot > 使用案例 >

spring-boot notes

邵耀
2023-12-01

Getting Started

Spring Boot helps you to create stand-alone, production-grade Spring-based applications that you
can run. We take an opinionated view of the Spring platform and third-party libraries, so that you
can get started with minimum fuss. Most Spring Boot applications need very little Spring
configuration.

spring-boot是spring的一个加强版,附带很多开箱即用的功能

Although there is nothing particularly special about Spring Boot (it is just
another library that you can consume), there are a few recommendations that, when followed,
make your development process a little easier.

think in spring,学习了解他的最佳实践和common ways make sense

Core Features

SpringApplication

FailureAnalyzer:没用到吧,写spring library的人会用到
java -jar myproject-0.0.1-SNAPSHOT.jar --debug

spring executable jar

Tasks expected to run during startup should be executed by CommandLineRunner and
ApplicationRunner components instead of using Spring component lifecycle callbacks
such as @PostConstruct.

If you need to access the application arguments that were passed to SpringApplication.run(…), you
can inject a org.springframework.boot.ApplicationArguments bean

一般都是通过环境变量获得。在backfill的情况下也是通过命令行获得。

If several CommandLineRunner or ApplicationRunner beans are defined that must be called in a specific
order, you can additionally implement the org.springframework.core.Ordered interface or use the
org.springframework.core.annotation.Order annotation.

Each SpringApplication registers a shutdown hook with the JVM to ensure that the
ApplicationContext closes gracefully on exit. All the standard Spring lifecycle callbacks (such as the
DisposableBean interface or the @PreDestroy annotation) can be used.

自动就有了啊

Externalized Configuration

You can use a variety of external configuration sources, include
Java properties files, YAML files, environment variables, and command-line arguments.

  • 配置文件
  • 环境变量
  • 命令行参数

主要是前两种

java -Dspring.application.json=‘{“my”:{“name”:“test”}}’ -jar myapp.jar
java -D定义System.getProperties
In most situations, each spring.config.location item you add will reference a single file or
directory. Locations are processed in the order that they are defined and later ones can override
the values of earlier ones.

If you use environment variables rather than system properties, most operating
systems disallow period-separated key names, but you can use underscores instead
(for example, SPRING_CONFIG_NAME instead of spring.config.name). See Binding from
Environment Variables for details.

. If several profiles are specified, a
last-wins strategy applies. For example, if profiles prod,live are specified by the
spring.profiles.active property, values in application-prod.properties can be overridden by those
in application-live.properties.

Property Placeholders
The values in application.properties and application.yml are filtered through the existing
Environment when they are used, so you can refer back to previously defined values (for example,
from System properties or environment variables). The standard ${name} property-placeholder
syntax can be used anywhere within a value. Property placeholders can also specify a default value
using a : to separate the default value from the property name, for example ${name:default}.

这就是在配置文件里面可以使用环境变量的原理
The properties that map to @ConfigurationProperties classes available in Spring
Boot, which are configured through properties files, YAML files, environment
variables, and other mechanisms, are public API but the accessors (getters/setters)
of the class itself are not meant to be used directly.

Spring Boot has dedicated support for expressing durations. If you expose a java.time.Duration
property, the following formats in application properties are available:
• A regular long representation (using milliseconds as the default unit unless a @DurationUnit has
been specified)
• The standard ISO-8601 format used by java.time.Duration
• A more readable format where the value and the unit are coupled (10s means 10 seconds)

In addition to durations, Spring Boot can also work with java.time.Period type. The following
formats can be used in application properties:
• An regular int representation (using days as the default unit unless a @PeriodUnit has been
specified)
• The standard ISO-8601 format used by java.time.Period
• A simpler format where the value and the unit pairs are coupled (1y3d means 1 year and 3 days)

Spring Framework has a DataSize value type that expresses a size in bytes. If you expose a DataSize
property, the following formats in application properties are available:
• A regular long representation (using bytes as the default unit unless a @DataSizeUnit has been
specified)
• A more readable format where the value and the unit are coupled (10MB means 10 megabytes)

这些默认的转换还是很牛逼的

Spring Boot attempts to validate @ConfigurationProperties classes whenever they are annotated
with Spring’s @Validated annotation. You can use JSR-303 javax.validation constraint annotations
directly on your configuration class.

Profiles

The spring.profiles.active property follows the same ordering rules as other properties: The
highest PropertySource wins. This means that you can specify active profiles in
application.properties and then replace them by using the command line switch.
Sometimes, it is useful to have properties that add to the active profiles rather than replace them.
The spring.profiles.include property can be used to add active profiles on top of those activated by
the spring.profiles.active property

Logging

In order to release logging resources when your application terminates, a shutdown hook that will
trigger log system cleanup when the JVM exits is provided. This shutdown hook is registered
automatically unless your application is deployed as a war file.

Tasks Exec and Scheduling

TaskExecutionProperties: default 8
TaskSchedulingProperties: default 1

Testing

Spring Boot includes a @MockBean annotation that can be used to define a Mockito mock for a bean
inside your ApplicationContext. You can use the annotation to add new beans or replace a single
existing bean definition
The annotation can be used directly on test classes, on fields within your
test, or on @Configuration classes and fields. When used on a field, the instance of the created mock
is also injected. Mock beans are automatically reset after each test method.

Additionally, you can use @SpyBean to wrap any existing bean with a Mockito spy

If you want to mock or spy on such a
bean, configure Mockito to use its inline mock maker by adding
org.mockito:mockito-inline to your application’s test dependencies. This allows
Mockito to mock and spy on final methods.

When you are using @SpyBean to spy on a bean that is proxied by Spring, you may need
to remove Spring’s proxy in some situations, for example when setting expectations
using given or when. Use AopTestUtils.getTargetObject(yourProxiedSpy) to do so.

Creating Your Own Auto-configuration

这个是重点

Under the hood, auto-configuration is implemented with the @AutoConfiguration annotation

Additional @Conditional annotations are used to constrain when the autoconfiguration should apply.

Concretely, a custom starter can contain the following:
• The autoconfigure module that contains the auto-configuration code for “acme”.
• The starter module that provides a dependency to the autoconfigure module as well as “acme”
and any additional dependencies that are typically useful. In a nutshell, adding the starter
should provide everything needed to start using that library.

The autoconfigure module contains everything that is necessary to get started with the library. It
may also contain configuration key definitions (such as @ConfigurationProperties) and any callback
interface that can be used to further customize how the components are initialized.

You can easily generate your own configuration metadata file from items annotated with
@ConfigurationProperties by using the spring-boot-configuration-processor jar.

Web

Under the hood, 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.
NOTE
You usually do not need to be aware of these implementation classes. Most
applications are auto-configured, and the appropriate ApplicationContext and
ServletWebServerFactory are created on your behalf.

Data

DataSource Configuration
DataSource configuration is controlled by external configuration properties in spring.datasource.*. For example, you might declare the following section in application.properties:

You should at least specify the URL by setting the spring.datasource.url property. Otherwise, Spring Boot tries to auto-configure an embedded database. see: spring-boot-starter-jdbc-2.4.2.pom

Redis

Redis is a cache, message broker, and richly-featured key-value store. Spring Boot offers basic auto-configuration for the Lettuce and Jedis client libraries and the abstractions on top of them provided by Spring Data Redis.

There is a spring-boot-starter-data-redis “Starter” for collecting the dependencies in a convenient way. By default, it uses Lettuce. That starter handles both traditional and reactive applications.

@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(RedisClient.class)
@ConditionalOnProperty(name = "spring.redis.client-type", havingValue = "lettuce", matchIfMissing = true)
class LettuceConnectionConfiguration extends RedisConnectionConfiguration {
	@Bean
	@ConditionalOnMissingBean(RedisConnectionFactory.class)
	LettuceConnectionFactory redisConnectionFactory(
			ObjectProvider<LettuceClientConfigurationBuilderCustomizer> builderCustomizers,
			ClientResources clientResources) {
		LettuceClientConfiguration clientConfig = getLettuceClientConfiguration(builderCustomizers, clientResources,
				getProperties().getLettuce().getPool());
		return createLettuceConnectionFactory(clientConfig);
	}
}

@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ GenericObjectPool.class, JedisConnection.class, Jedis.class })
@ConditionalOnMissingBean(RedisConnectionFactory.class)
@ConditionalOnProperty(name = "spring.redis.client-type", havingValue = "jedis", matchIfMissing = true)
class JedisConnectionConfiguration extends RedisConnectionConfiguration {
	@Bean
	JedisConnectionFactory redisConnectionFactory(
			ObjectProvider<JedisClientConfigurationBuilderCustomizer> builderCustomizers) {
		return createJedisConnectionFactory(builderCustomizers);
	}
}

根据这个配置,
1, 自定义了JedisConnectionFactory, 使用自定义的
2,不存在spring.redis.client-type或者spring.redis.client-type=lettuce, 使用lettuce
3,只有spring.redis.client-type=jedis,使用jedis
4, spring.redis.client-type = xxx,报错

Production-ready Features

You can enable or disable each individual endpoint and expose them (make them remotely
accessible) over HTTP or JMX. An endpoint is considered to be available when it is both enabled
and exposed

Enabling Endpoints
By default, all endpoints except for shutdown are enabled. To configure the enablement of an
endpoint, use its management.endpoint..enabled property. The following example enables the
shutdown endpoint:
.
management.endpoint..enabled: 只是enable这个actuator,但不是expose
Property Default
management.endpoints.jmx.exposure.exclude
management.endpoints.jmx.exposure.include *
management.endpoints.web.exposure.exclude
management.endpoints.web.exposure.include health

所以默认只能在/actuator看到health,要看到左右信息,需要设置

management:
  endpoints:
    web:
      exposure:
        include: '*'

If you want to implement your own strategy for when endpoints are exposed, you can
register an EndpointFilter bean.
Implementing Custom Endpoints
If you add a @Bean annotated with @Endpoint, any methods annotated with @ReadOperation,
@WriteOperation, or @DeleteOperation are automatically exposed over JMX and, in a web application,
over HTTP as well.Writing Custom HealthIndicators
To provide custom health information, you can register Spring beans that implement the
HealthIndicator interface.

Metrics
Spring Boot auto-configures a composite MeterRegistry and adds a registry to the composite for
each of the supported implementations that it finds on the classpath. Having a dependency on
micrometer-registry-{system} in your runtime classpath is enough for Spring Boot to configure the
registry.

spring-boot很多情况就是这样,不仅要有对应的配置项,还需要自己手动的加上对应的dependency

 类似资料: