Spring Boot 2.x basic tutorial
- 1. Introduction
- 2. Spring Boot 2.x environment construction
- 3. Core functions
- 4. Data access
- 5. Spring Boot 2.x and Web
- 6. Spring Boot 2.x advanced features
1. Introduction
1. Introduction to Spring Boot 2.x
Spring Boot is a rapid web development framework based on the Spring framework, built using a convention-over-configuration approach. It simplifies the development process of Spring applications and continuously launches new versions to meet current development needs.
2. Spring Boot 2.x features
- Simplify the Spring application development process
- Automatically configure Spring applications
- Embedded Servlet container, no need to deploy war package
- Provides management endpoints to monitor application health
- Supports the integration of various components, such as ORM, template engine, etc.
3. The relationship between Spring Boot 2.x and Spring Framework
Spring Boot is a framework built on the Spring Framework. Among them, Spring Framework provides basic IoC, AOP, events, data access, Web framework and testing support; while Spring Boot encapsulates Spring Framework, further simplifying the construction of Spring applications.
2. Spring Boot 2.x environment construction
1. JDK environment installation and configuration
First, you need to install Java Development Kit (JDK). You can download and install the latest version of JDK through Oracle's official website, and then configure the JDK installation path in the environment variable.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.5.0</version>
</dependency>
2. Maven environment installation and configuration
Next, Maven needs to be installed. You can download and install the latest version of Maven through the Apache official website, and then configure the Maven installation path in the environment variables.
3. Spring Boot 2.x project creation
Finally, you can use Spring Initializr to create a Spring Boot project. On the official website of Spring Initializr (https://start.spring.io/), select the required project configuration and dependencies, and then click "Generate". The generated project contains basic Spring Boot configuration and dependencies and can be used directly for development.
3. Core functions
1. Configuration files and their loading order
a. YAML file format
# YAML配置文件示例
server:
port: 8080
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
username: root
password: test
Note: Configure the related properties through the file, which is YAML
the database connection property configuration.server
spring
datasource
b. Property configuration file (.properties)
# .properties配置文件示例
server.port=8080
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=test
Note: Configure related properties through .properties
the configuration file , among which are the database connection properties.server
spring
datasource
2. Log management
a. Spring Boot log framework selection
Spring Boot uses logback for log output by default. You can also switch to other logging frameworks, such as Log4j2 or JUL.
b. Custom log
Use Slf4j to encapsulate log content and output it with the corresponding log framework.
// 引入Slf4j
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
@Service
@Slf4j
public class UserService {
public void login(String username, String password) {
log.info("用户{}正在登录...", username);
// do something
}
}
Note: Use annotations to introduce Slf4j log encapsulation, and use other methods to @Slf4j
output logs where needed .log.info
3. Spring Boot 2 hot deployment implementation
a. Introduction of devtools
Using devtools
the hot deployment function that can implement Spring Boot projects can improve debugging efficiency during the development phase.
<!-- 引入devtools依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
Note: By Maven
introducing devtools
dependencies.
b. Usage methods and precautions
Add the following properties to the configuration file:
# 配置热部署属性
spring.devtools.restart.enabled=true
spring.devtools.restart.exclude=static/**,public/**
Note: When using it, you need to manually compile the code once to take effect.
4. AOP in Spring Boot 2.x
a. Definition and use of aspects
Use @Aspect
annotations to define aspect classes, use @Before
, @After
, @Around
and other annotations to define different types of notifications, and @Pointcut
define cut points through annotations. as follows:
// 定义切面类
@Aspect
@Service
@Slf4j
public class LogAspect {
// 定义切点
@Pointcut("execution(* com.example.demo.service..*.*(..))")
public void point() {
}
// 定义前置通知
@Before("point()")
public void before() {
log.info("before aspect.");
}
// 定义后置通知
@After("point()")
public void after() {
log.info("after aspect.");
}
// 定义环绕通知
@Around("point()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
log.info("before around aspect.");
Object obj = joinPoint.proceed();
log.info("after around aspect.");
return obj;
}
}
Use aspects:
@Service
@Slf4j
public class UserService {
@Autowired
private UserDao userDao;
// 使用切面
@LogAspect
public void login(String username, String password) {
log.info("用户{}正在登录...", username);
// do something
}
}
Note: Use @Aspect
annotations to define aspect classes, @Pointcut
define pointcuts through annotations, use @Before
, @After
, @Around
and other annotations to define different types of notifications. Just add custom annotations to the methods that need to use aspects.
4. Data access
1. Spring Boot 2.x and JPA
a. Introduction to JPA
JPA is the abbreviation of Java Persistence API. It is a set of ORM specifications that provide developers with a simple and elegant way to manage relational data in Java applications.
b. Spring Boot 2.x uses JPA basic configuration
To use JPA in a Spring Boot project, you need to add the following dependencies:
<!-- 引入JPA相关依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
At the same time, configure the database in the configuration file:
# jpa 数据库配置
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.username=root
spring.datasource.password=test
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
Note: By Maven
introducing spring-boot-starter-data-jpa
dependencies and configuring the database in the configuration file.
2. Spring Boot 2.x and MyBatis
a. Introduction to MyBatis
MyBatis is a persistence layer ORM framework that encapsulates the JDBC database operation process and provides a simpler, easier-to-read, and easier-to-maintain method.
b. Spring Boot 2.x integrates MyBatis
To integrate MyBatis in the Spring Boot project, you need to add the following dependencies:
<!-- 引入Mybatis相关依赖 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
At the same time, configure the database in the configuration file:
# MyBatis及数据库配置
# MyBatis的mapper文件的路径
mybatis.mapper-locations=classpath:mapper/*.xml
# 数据源配置
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=test
Note: By Maven
introducing mybatis-spring-boot-starter
dependencies and configuring the database in the configuration file.
3. Spring Boot 2.x and Druid data source
a. Introduction to Druid
Druid is a database connection pool implementation on the Alibaba open source platform. It combines the advantages of DB connection pools such as C3P0 and DBCP, and also adds log monitoring.
b. Spring Boot 2.x integrates Druid
To integrate Druid in a Spring Boot project, you need to add the following dependencies:
<!-- 引入Druid相关依赖 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.5</version>
</dependency>
At the same time, configure the database in the configuration file:
# druid 数据库配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=test
# druid 配置
spring.datasource.druid.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.druid.initial-size=1
spring.datasource.druid.min-idle=1
spring.datasource.druid.max-active=20
spring.datasource.druid.max-wait=60000
spring.datasource.druid.time-between-eviction-runs-millis=60000
spring.datasource.druid.min-evictable-idle-time-millis=300000
spring.datasource.druid.validation-query=SELECT 1 FROM DUAL
spring.datasource.druid.test-while-idle=true
spring.datasource.druid.test-on-borrow=false
spring.datasource.druid.filters=stat,wall
Note: By Maven
introducing druid-spring-boot-starter
dependencies and configuring the database in the configuration file.
5. Spring Boot 2.x and Web
1. Spring Boot 2.x Web Encapsulation
a. Spring Boot comes with a web application server
Spring Boot will use embedded Tomcat as the web application server by default without external deployment. Of course, you can also use Jetty or Undertow as alternatives.
b. Four common responses
There are usually the following 4 common response methods in Spring Boot:
1. Return Model layer data
@GetMapping("/model")
public String model(Model model) {
model.addAttribute("name", "John");
return "hello";
}
In the above code, we set the attribute "name" in the Model object to "John", and then return a template named "hello". Spring Boot will automatically render the corresponding HTML based on the template.
2. Return the string directly
@GetMapping("/response")
@ResponseBody
public String response() {
return "Hello World!";
}
In the above code, we directly return a string "Hello World!", and Spring Boot will convert it into an HTTP Response and output it to the client.
3. Return JSON data
@GetMapping("/json")
@ResponseBody
public Map<String, Object> json() {
Map<String, Object> map = new HashMap<>();
map.put("name", "John");
map.put("age", 30);
map.put("gender", "Male");
return map;
}
In the above code, we return a Map type JSON data, which contains three attributes: name, age and gender.
4. Return HTTP status code
@GetMapping("/status")
public ResponseEntity<String> status() {
return new ResponseEntity<>("Hello World!", HttpStatus.OK);
}
In the above code, we return an HTTP OK status and carry the string "Hello World!".
2. Spring Boot 2.x and JSP
a. Introduction to JSP
JSP (Java Server Pages) is a technology that embeds Java code in HTML (or XML) documents. It is a wrapper on top of the Servlet API and can be used to develop dynamic web pages.
JSP allows you to embed Java code in HTML pages so that you can display dynamic content on the page.
b. Spring Boot 2.x uses JSP
First, add dependency on jsp support and Tomcat Embed Jasper in the project's pom.xml:
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
Add the following configuration in application.properties:
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
Create JSP file (/src/main/webapp/WEB-INF/jsp/hello.jsp):
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello JSP</title>
</head>
<body>
<h1>Hello, <%= request.getAttribute("name") %>!</h1>
</body>
</html>
Add Controller code:
@Controller
public class HelloController {
@RequestMapping("/hello")
public String hello(Model model) {
model.addAttribute("name", "John");
return "hello";
}
}
Just visit http://localhost:8080/hello.
3. Spring Boot 2.x static resource processing
a. Static resource access
Spring Boot 2.x will look for static resources in the following path by default:
classpath:/META-INF/resources/
classpath:/resources/
classpath:/static/
classpath:/public/
For example, you can src/main/resources/static/
create an logo.png
image file named in a directory and http://localhost:8080/logo.png
access it via a URL.
6. Spring Boot 2.x advanced features
1. Spring Boot 2.x Actuator extension
a. The role of actuator
Actuator is used to monitor and manage Spring Boot applications. It provides many functions for checking application health, including application health, indicator collection and exposure, log configuration and other functions.
b. How to use actuator
-
Introduce actuator dependencies in pom.xml:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
-
Turn on or off the Actuator function in the application.properties file:
management.endpoint.health.show-details=always
The above example indicates that the health check function is enabled and detailed information is displayed.
-
Visit the following URL to view Actuator's feature list:
http://localhost:8080/actuator
2. Spring Boot 2.x multi-environment configuration
a. Execution environment classification
There are four types of Spring Boot environment definitions:
- development
- testing
- staging
- production
b. Priority of configuration files
Spring Boot supports multiple profile configuration files. The file name must be named after application-{profile}.properties, where profile can be one of the above environment categories.
When there are multiple profiles, the priority of the profile from high to low is as follows:
- application-{profile}.yml
- application-{profile}.properties
- application.yml
- application.properties
3. Spring Boot 2.x integrates Quartz
a. Introduction to Quartz
Quartz is a powerful job scheduling framework that can be used to create simple or complex scheduled tasks and supports cluster and distributed deployment.
b. Spring Boot 2.x integrates Quartz
-
Introduce the dependencies of quartz and quartz-jobs in pom.xml:
<dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.3.1</version> </dependency> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz-jobs</artifactId> <version>2.3.1</version> </dependency>
-
Configure Quartz in the application.properties file:
# Quartz 配置 spring.quartz.job-store-type=jdbc spring.quartz.jdbc.initialize-schema=always spring.quartz.properties.org.quartz.threadPool.threadCount=10
-
Create Job class:
@Component public class MyJob implements Job { @Override public void execute(JobExecutionContext context) throws JobExecutionException { // 需要执行的任务逻辑 } }
-
Create JobDetail and Trigger and register them with Scheduler:
@Configuration public class QuartzConfig { @Autowired private MyJob myJob; @Bean public JobDetail jobDetail() { return JobBuilder.newJob(myJob.getClass()) .withIdentity("myJob") .storeDurably() .build(); } @Bean public Trigger trigger(JobDetail job) { return TriggerBuilder.newTrigger() .forJob(job) .withIdentity("myJobTrigger") .withSchedule(CronScheduleBuilder.cronSchedule("0 0 12 * * ?")) .build(); } @Bean public Scheduler scheduler(Trigger trigger, JobDetail job, DataSource dataSource) throws SchedulerException { SchedulerFactory schedulerFactory = new StdSchedulerFactory(); Scheduler scheduler = schedulerFactory.getScheduler(); scheduler.setDataSource(dataSource); scheduler.scheduleJob(job, trigger); return scheduler; } }