Spring 课程笔记

课程概述

课程主要关注的三个内容

  • Spring framework
  • Spring boot
  • Spring cloud

第一章 初识 Spring

编写第一个 Spring 程序,使用 spring 官网提供的 spring initializr 工具,填写对应的配置后,即可生成一个 spring 程序的骨架。
https://start.spring.io

这里添加了 web 和 spring actuator 两个依赖。

用 idea 打开后,直接在生成的 springbootapplication 类中进行修改,添加 restcontroller 注解,并添加一个 hello path 的 requestMapping 即可完成一个最简单的 spring 程序。

1
2
3
4
5
6
7
8
9
10
11
12
13
@SpringBootApplication
@RestController
public class HelloSpringApplication {

public static void main(String[] args) {
SpringApplication.run(HelloSpringApplication.class, args);
}

@RequestMapping("/hello")
public String hello() {
return "Hello Spring";
}
}

可以直接运行在内嵌的 tomcat 容器中。

访问 curl http://localhost:8080/hello 即可看到运行结果 Hello Spring%
访问 curl http://localhost:8080/actuator/health 可看到节点的健康状态 {"status":"UP"}%

还可以使用 mvn clean package -Dmaven.test.skip 命令,将 spring 程序打包成 jar 文件
生成的jar包
其中,较大的那个 jar 包是 spring 自动将程序所需的依赖也打包的结果。因此可以直接使用 java -jar 命令运行
java -jar target/hello-spring-0.0.1-SNAPSHOT.jar

假如因为某些原因无法使用 spring-boot-starter-parent 作为项目的 parent,那么只需要按下面这样修改下 pom 文件即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.5</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
...
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.7.5</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>

即,添加一个 dependencyManagement 标签,将 spring-boot-starter-parent 完整的导入进来,并在下面的 spring-boot-maven-plugin 添加配置,声明在 repackage 的时候引入。

第二章 JDBC 必知必会

如何配置单数据源

构建项目骨架,引入的依赖有

  • Actuator 监控状态
  • H2 数据库
  • JDBC 操作数据库
  • Lombok 提供一些注解
  • Web 以 web 形式启动,方便访问一些 Actuator 的一些 url

showConnection

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
@SpringBootApplication
@Slf4j
public class DatasourcedemoApplication implements CommandLineRunner {
@Autowired
private DataSource dataSource;

@Autowired
private JdbcTemplate jdbcTemplate;

public static void main(String[] args) {
SpringApplication.run(DatasourcedemoApplication.class, args);
}

@Override
public void run(String... args) throws Exception {
showConnection();
showData();
}

private void showData() {
jdbcTemplate.queryForList("SELECT * FROM FOO")
.forEach(row -> log.info(row.toString()));
}

private void showConnection() throws SQLException {
log.info(dataSource.toString());
Connection conn = dataSource.getConnection();
log.info(conn.toString());
conn.close();
}
}

运行后,可以看到 spring boot 自动配置了数据源 HikariDataSource,并连接到内存数据库 h2 HikariProxyConnection@395257482 wrapping conn0: url=jdbc:h2:mem:9c9048f5-ff8c-48fd-9f1d-837bd639a404 user=SA

可以打开浏览器,访问 http://localhost:8080/actuator/beans 可以看到所有的 Bean,但是 web 模式下,actuator 默认暴露的 endpoint 只有 health,参见:https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#actuator.endpoints.exposing。

因此,需要先打开 beans 的暴露,在 application.properties 中添加配置 management.endpoints.web.exposure.include=health,beans 即可。

resources 目录下新建的 schema.sql 和 data.sql 会被 Spring Boot 自动加载,然后 showData 的代码会打印出数据库中的两行由 data.sql 插入的数据。

数据源相关配置属性
通用

  • spring.datasource.url=jdbc:mysql://localhost/test
  • spring.datasource.username=dbuser
  • spring.datasource.password=dbpass
  • spring.datasource.driver-class-name=com.mysql.jdbc.Driver(可选)

初始化内嵌数据库

  • spring.datasource.initialization-mode=embedded(默认值,只初始化内存数据库)|always(总是初始化数据库)|never(不初始化数据库)
  • spring.datasource.schema与spring.datasource.data确定初始化SQL文件
  • spring.datasource.platform=hsqldb | h2 | oracle | mysql | postgresql(与前者对应)

演示 demo 中的 application.properties 的配置

1
2
3
4
5
6
7
8
9
10
11
management.endpoints.web.exposure.include=*
spring.output.ansi.enabled=ALWAYS

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.hikari.maximumPoolSize=5
spring.datasource.hikari.minimumIdle=5
spring.datasource.hikari.idleTimeout=600000
spring.datasource.hikari.connectionTimeout=30000
spring.datasource.hikari.maxLifetime=1800000

配置多个数据源

注意事项

  • 不同数据源的配置要分开
  • 关注每次使用的资源
    • 有多个 DataSource 时系统如何判断
    • 对应的设施(事务、ORM 等)如何选择 DataSource

配置方式

方法一 手工配置两组 DataSource 及相关内容
方法二 与 Spring Boot 协同工作

  • 配置 @Primary 类型的 Bean: 配置了该注解的 DataSource 作为主要的 DataSource,Spring Boot 的配置将围绕该 DataSource 进行
  • 排除 Spring Boot 的自动配置
    • DataSourceAutoConfiguration
    • DataSourceTransactionManagerAutoConfiguration
    • JdbcTemplateAutoConfiguration

操作记录

构建项目 multidatasourcedemo ,引入的依赖有

  • Actuator 监控状态
  • H2 数据库
  • JDBC 操作数据库
  • Lombok 提供一些注解
  • Web 以 web 形式启动,方便访问一些 Actuator 的一些 url

application.properties 配置如下

1
2
3
4
5
6
7
8
9
10
management.endpoints.web.exposure.include=*
spring.output.ansi.enabled=ALWAYS

foo.datasource.url=jdbc:h2:mem:foo
foo.datasource.username=sa
foo.datasource.password=

bar.datasource.url=jdbc:h2:mem:bar
bar.datasource.username=sa
bar.datasource.password=

排除 Spring boot 自动配置

1
2
3
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class,
JdbcTemplateAutoConfiguration.class})

配置数据源

  1. 配置 DataSourceProperties
  2. 配置 DataSource
  3. 配置 PlatformTransactionManager
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Bean
@ConfigurationProperties("foo.datasource")
public DataSourceProperties fooDataSourceProperties() {
return new DataSourceProperties();
}

@Bean
public DataSource fooDataSource() {
DataSourceProperties dataSourceProperties = fooDataSourceProperties();
log.info("foo datasource: {}", dataSourceProperties.getUrl());
return dataSourceProperties.initializeDataSourceBuilder().build();
}

@Bean
@Resource
public PlatformTransactionManager fooTxManager(DataSource fooDataSource) {
return new DataSourceTransactionManager(fooDataSource);
}

HikariCP

性能很快:字节码优化和很多的小改进的累积

  • Spring 1.x 默认使用的 Tomcat 连接池,要使用 HikariCP 的话,需要移除 tomcat-jdbc 依赖,配置 spring.datasource.type=com.zaxxer.hikari.HikariDataSource
  • Spring 2.x 默认使用的就是 HikariCP 连接池了,可以直接配置 spring.datasource.hikari.*

HikariCP 常用配置

1
2
3
4
5
spring.datasource.hikari.maximumPoolSize=5
spring.datasource.hikari.minimumIdle=5
spring.datasource.hikari.idleTimeout=600000
spring.datasource.hikari.connectionTimeout=30000
spring.datasource.hikari.maxLifetime=1800000

官网:https://github.com/brettwooldridge/HikariCP

打赏
  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!
  • Copyrights © 2022 qusong
  • 访问人数: | 浏览次数:

请我喝杯咖啡吧~

支付宝
微信