Table of contents
1. First introduction to SpringBoot
2.1 Integrate Mybatis framework
2.2 Integrate Pagehepler paging plug-in
2.3 Integrate Druid database connection pool
1. First introduction to SpringBoot
1.1 Introduction
Spring Boot is a framework for simplifying Spring application development, providing a way to quickly develop and simplify configuration. Spring Boot uses the principle that convention is greater than configuration to minimize developers' work in project configuration.
In Spring Boot, you can introduce the required functions through simple configuration, without manually configuring a large number of XML files or Java code. It also provides some commonly used dependencies to facilitate you to quickly build various types of applications, such as web applications, RESTful services, batch processing, etc.
1.2 Project creation
官方:Getting Started | Building an Application with Spring Boot
1. Local creation example:
2. Change data source
This is the default springboot project creation interface. Here you need to note that the default Server URL address ishttps://start .spring.io/ This address requires a higher JDK (Java 17 or above).
The blogger uses Java8, so he changed the data source of Alibaba Cloud:https://start.aliyun.com/
Of course, you can also go to this URL to download the project:
3. Choose dependencies
After clicking NEXT, the following interface will appear: allowing you to select some toolkits needed for the project
1.3 Directory structure
Click CREATE You can see the project structure after creationThere is no /WEB-INF directory,The Spring Boot project does not need to be included directly< /span> configuration file. /META-INF
directory, because Spring Boot advocates convention over configuration, a lot of configuration information has been integrated into the application.yml
-
src/main/java: Main program entry BootApplication, you can start the SpringBoot application by running this class directly
-
src/main/resources: Configuration directory, which is used to store some configuration information of the application, such as application name, service port, database configuration, etc. Since we applied the Web module, a static directory was created. The former is used to store static resources, such as images, CSS, JavaScript, etc.; the latter is used to store template files of Web pages.
-
src/test: Unit test directory. The generated ApplicationTests are implemented through JUnit4 and can be used to directly run the tests of SpringBoot applications.
-
application.properties/application.yml: used to store the configuration information of various dependent modules of the program, such as service port, database connection configuration, etc.
1.4 Modify configuration
First we need to see the configuration fileThe format is properties,In actual application, a large amount of configuration information in this format is obviously It is not concise and clear enough, so it needs to be modified into yml format.
Here I recommend a plug-in that can convert between these two formats with one click:Convert YAML and Properties File
Right-clicking the configuration file will bring up this option:
Then convert it to this format
Here you need to write it in this format, otherwise the specified configuration information will not be found;
Error example:
1. The datasource is not configured under spring.
2. url: no space after it
2. SpringBoot integration
2.1 Integrate Mybatis framework
application.yml
mybatis:
# mapper.xml所在的位置
mapper-locations: classpath:mappers/*xml
type-aliases-package: com.ycxw.boot.entity
server:
port: 8080
spring:
#数据源配置
datasource:
url: jdbc:mysql://localhost:3306/bookshop
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
idea connects to database:
mybatis generates code:
The final project structure and running tests written:
Note:After configuring mybatis and writing the code interface, this error will appear when running the project. The reason is that the mapper package is not scanned in the startup class
Solution:Add this comment in the startup class
@MapperScan("com.ycxw.boot.mapper")package com.ycxw.boot; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @MapperScan("com.ycxw.boot.mapper") @SpringBootApplication public class BootApplication { public static void main(String[] args) { SpringApplication.run(BootApplication.class, args); } }
2.2 Integrate Pagehepler paging plug-in
application.yml
pagehelper:
# 配置方言
helperDialect: mysql
# 分页合理化
reasonable: true
# mapper方法上的分页参数
supportMethodsArguments: true
# 查询数量
params: count=countSql
Controller:
package com.ycxw.boot.controller;
import com.github.pagehelper.PageHelper;
import com.ycxw.boot.page.PageBean;
import com.ycxw.boot.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author 云村小威
* @create 2023-12-12 14:59
*/
@RestController
@RequestMapping("/book")
public class BookController {
@Autowired
private BookService bookService;
@RequestMapping("/list")
public Object list(PageBean pageBean) {
PageHelper.startPage(pageBean.getPage(),pageBean.getRows());
return bookService.list();
}
}
Before this, you need to import the prepared paging tool class. Currently, if you write it like this, you have to adjust the paging method every time, so you can configure the AOP aspect to realize the global paging function.
test:
2.3 Integrate Druid database connection pool
To sum up, the schema Druid connection pool is the best, and spring comes with the HikariCP connection pool, so we need to replace it.
application.yml:
spring:
#数据源配置
datasource:
url: jdbc:mysql://localhost:3306/bookshop
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
druid:
# 初始化时建立物理连接的个数
initial-size: 5
# 最小连接池数量
min-idle: 5
# 最大连接池数量
max-active: 20
#配置获取连接等待超时的时间
max-wait: 60000
#配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
time-between-eviction-runs-millis: 60000
# 一个连接在池中最小生存的时间,单位是毫秒
min-evictable-idle-time-millis: 30000
# 用来检测连接是否有效的 sql,要求是一个查询语句
validation-query: SELECT 1 FROM DUAL
# 建议配置为 true,不影响性能,并且保证安全性
test-while-idle: true
# 申请连接时执行 validationQuery 检测连接是否有效
test-on-borrow: true
# 归还连接时执行 validationQuery 检测连接是否有效
test-on-return: false
# 是否缓存 preparedStatement,即 PsCache
# PSCache 对支持游标的数据库性能提升巨大,比如说 oracle,而 mysql 则建议关闭
pool-prepared-statements: true
# 要启用 PSCache,必须配置大于0
max-pool-prepared-statement-per-connection-size: 20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计
filter:
stat:
merge-sql: true
slow-sql-millis: 5000
# 基础监控配置
web-stat-filter:
enabled: true
url-pattern: /*
exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
session-stat-enable: true
session-stat-max-count: 100
stat-view-servlet:
enabled: true
url-pattern: /druid/*
reset-enable: true
login-username: admin #设置监控页面的登录名和密码
login-password: 123456
allow: 127.0.0.1 #deny: 192.168.1.100
Druid has a different advantage in that it can monitor projects. Monitoring information has been configured in Druid throughhttp://localhost:8080/druid/ To access, you must first log in (the account and password can be modified by yourself)
After successful login, you can see project-related data:
2.4 Integrated Log management
In order to be able to see the information and SQL statements of our calling methods in real time during development, log management needs to be configured.
application.yml:
#log日志配置
logging:
level:
#指定项目目录输入日志信息
com.ycxw.boot.mapper: debug
The log level of a specific package (com.ycxw.boot.mapper
) is set to debug
.
Set the log level for a package to
debug
during development to get a more detailed understanding of system behavior, and set it to a lower level in production, like < /span> to reduce redundant information.info
orwarn
Finally, the log information will be printed on the console: