Springboot框架學習:從入門到初級應用教程
Spring Boot框架学习涵盖了从环境搭建到核心概念解析的全过程,包括搭建开发环境、创建第一个Spring Boot项目、理解核心注解、配置文件管理以及构建RESTful服务等。此外,还详细介绍了Spring Boot与数据库的集成、数据访问和集成、模板引擎与静态资源处理,以及日志与异常处理机制。通过这些内容,读者可以全面地掌握Spring Boot框架的使用方法。
Spring Boot简介与环境搭建Spring Boot是什么
Spring Boot是由Pivotal团队提供的全新框架,其设计目的是简化Spring应用的初始搭建以及开发过程。它通过采取约定优于配置的方式,来减少项目的配置文件量。同时,Spring Boot也为开发人员提供了一系列开箱即用的功能,如自动配置、嵌入式Web服务器集成、开发工具集成等,大幅度降低了应用开发的门槛。
开发环境搭建
安装JDK
首先,确保你的计算机已经安装了Java开发工具包(JDK)。Spring Boot应用程序需要运行在支持Java的应用程序环境中。你可以从Oracle官网或OpenJDK下载页面下载JDK安装包,并按照安装向导完成安装。
安装IDE
为了编写和调试Spring Boot应用程序,你需要一个合适的集成开发环境(IDE)。推荐使用IntelliJ IDEA或Eclipse。这些IDE都对Spring Boot有很好的支持,提供了许多便利的功能,如自动代码完成、错误检查等。
下载Spring Boot Starter
Spring Boot Starter是一个依赖管理工具,可以简化依赖管理。为了方便开发人员,Spring Boot提供了多个Starter依赖,如spring-boot-starter-web
用于Web开发,spring-boot-starter-data-jpa
用于JPA操作等。你可以在Maven或Gradle的依赖管理文件中直接引入这些Starter依赖,从而快速搭建项目。
创建第一个Spring Boot项目
项目结构
一个典型的Spring Boot项目结构如下:
src
├── main
│ ├── java
│ │ └── com
│ │ └── example
│ │ └── demo
│ │ ├── DemoApplication.java
│ │ └── controller
│ │ └── HelloController.java
│ └── resources
│ └── application.properties
└── test
└── java
└── com
└── example
└── demo
└── DemoApplicationTests.java
创建Spring Boot项目
你可以使用Spring Initializr在线工具或者IDE的插件来创建Spring Boot项目。这里以IntelliJ IDEA为例:
- 打开IntelliJ IDEA,进入
File
->New
->Project
。 - 选择
Spring Initializr
,点击Next
。 - 在
Spring Initializr
中填写Group
和Artifact
,并选择Java
和Maven
。 - 选择
Spring Boot
版本,这里推荐使用最新稳定版。 - 在
Dependencies
列表中选择需要的Starter依赖,如web
、data-jpa
等。 - 点击
Next
,选择项目保存路径,点击Finish
完成项目创建。
运行第一个Spring Boot应用
编辑DemoApplication.java
文件,创建一个简单的Spring Boot应用入口:
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
@SpringBootApplication
注解是一个组合注解,等价于@Configuration
、@EnableAutoConfiguration
和@ComponentScan
。@Configuration
:该注解标记类为一个Spring配置类,允许包含配置和bean定义。@EnableAutoConfiguration
:允许Spring Boot根据类路径中的依赖来自动配置应用。@ComponentScan
:自动扫描并注册标记了@Component
、@Service
、@Repository
等注解的类作为Spring Bean。
在src/main/resources
目录下创建application.properties
文件,添加一些基本配置:
server.port=8080
spring.application.name=demo-app
运行DemoApplication.java
中的main
方法,启动应用。默认情况下,应用将监听8080端口。可以通过浏览器访问http://localhost:8080
来测试应用是否成功启动。
核心注解详解
Spring Boot中的一些核心注解对于理解和使用框架非常重要。这里介绍一些常用的注解。
@SpringBootApplication
@SpringBootApplication
注解是一个组合注解,集成了@Configuration
、@EnableAutoConfiguration
和@ComponentScan
三个注解。它通常用于主入口类,表示这是一个Spring Boot应用的入口类。
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
@Configuration
@Configuration
是一个Java注解,表示该类是一个配置类,可以包含配置信息和bean定义。通过@Bean
注解定义的函数会返回一个bean实例。
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyServiceImpl();
}
}
@ComponentScan
@ComponentScan
注解用于指定需要扫描的包范围,Spring会自动扫描带有@Component
、@Service
、@Repository
等注解的类,并注册为Spring Bean。
@ComponentScan(basePackages = "com.example.demo")
public class AppConfig {
}
@EnableAutoConfiguration
@EnableAutoConfiguration
注解用于开启自动配置功能,根据类路径中的依赖来自动配置应用。
@EnableAutoConfiguration
public class AppConfig {
}
自动配置机制
Spring Boot的自动配置机制是其一大亮点。自动配置可以根据项目中引入的依赖,自动配置所需的bean。以下是一些常见的自动配置场景:
-
Web应用自动配置
如果项目中引入了
spring-boot-starter-web
依赖,Spring Boot会自动配置一个Tomcat
内嵌服务器,并设置默认的DispatcherServlet
,处理HTTP请求。import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class WebApplication { public static void main(String[] args) { SpringApplication.run(WebApplication.class, args); } }
-
数据源和事务管理
如果项目中引入了
spring-boot-starter-data-jpa
依赖,Spring Boot会自动配置一个数据源和事务管理器,并根据配置文件自动配置JPA
的实体管理器。import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class JpaApplication { public static void main(String[] args). SpringApplication.run(JpaApplication.class, args); }
-
邮件发送
如果项目中引入了
spring-boot-starter-mail
依赖,Spring Boot会自动配置邮件发送相关的bean,并根据配置文件中的邮件服务器设置自动配置邮件发送器。import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration; @SpringBootApplication public class MailApplication { public static void main(String[] args) { SpringApplication.run(MailApplication.class, args); } }
配置文件使用与管理
Spring Boot支持多种配置文件格式,如properties
、YAML
等。常用的配置文件是application.properties
或application.yml
,放在src/main/resources
目录下。
application.properties
配置文件包含了应用的各种设置,如端口号、数据库连接信息等。以下是一些常见的配置项:
# 应用名称
spring.application.name=myapp
# 端口号
server.port=8080
# 数据库配置
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=admin
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# JPA配置
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
application.yml
YAML
格式的配置文件使用缩进表示层级关系,更加简洁。以下是一个YAML
格式的配置文件示例:
spring:
application:
name: myapp
port: 8080
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: root
password: admin
driver-class-name: com.mysql.jdbc.Driver
jpa:
hibernate:
ddl-auto: update
show-sql: true
外部化配置
Spring Boot支持外部化配置,可以通过命令行参数、环境变量、application.properties
等外部文件来覆盖配置文件中的值。例如,在命令行中通过--server.port=8081
来覆盖默认的端口号。
创建RESTful API
RESTful API是一种基于REST架构风格的API设计规范,它定义了一组资源及其操作。Spring Boot提供了非常方便的方式来创建RESTful API。
首先,创建一个简单的资源类:
package com.example.demo.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
// 构造函数、getter和setter省略
}
然后,创建一个控制器类来处理HTTP请求:
package com.example.demo.controller;
import com.example.demo.model.User;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/api/users")
public class UserController {
private List<User> users = new ArrayList<>();
@GetMapping
public List<User> getUsers() {
return users;
}
@PostMapping
public User createUser(@RequestBody User user) {
users.add(user);
return user;
}
@GetMapping("/{id}")
public User getUserById(@PathVariable Long id) {
return users.stream().filter(user -> user.getId().equals(id)).findFirst().orElse(null);
}
@PutMapping("/{id}")
public User updateUser(@PathVariable Long id, @RequestBody User user) {
User existingUser = users.stream().filter(user1 -> user1.getId().equals(id)).findFirst().orElse(null);
if (existingUser != null) {
existingUser.setName(user.getName());
existingUser.setEmail(user.getEmail());
}
return existingUser;
}
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable Long id) {
users.removeIf(user -> user.getId().equals(id));
}
}
@RestController
@RestController
注解是@Controller
和@ResponseBody
的组合,用于标记一个控制器类。该控制器类中的方法返回的对象会直接作为HTTP响应体返回,而不需要通过视图解析器来解析。
@RequestMapping
@RequestMapping
注解用于映射Web请求到控制器中的处理方法。它可以通过value
属性指定请求的URL路径,也可以通过method
属性指定请求的方法(如GET、POST等)。
@GetMapping
、@PostMapping
、@PutMapping
、@DeleteMapping
这些注解是@RequestMapping
的特殊形式,分别映射HTTP GET、POST、PUT、DELETE请求。
使用Spring Boot处理HTTP请求
Spring Boot提供了多种注解来处理HTTP请求,如@GetMapping
、@PostMapping
、@PutMapping
、@DeleteMapping
等。这些注解不仅可以映射请求的方法,还可以指定请求的URL路径、请求参数等。
请求参数
你可以使用@RequestParam
注解来获取请求中的参数值。例如:
@GetMapping("/users/{id}")
public User getUserById(@PathVariable Long id, @RequestParam String param) {
// 使用id和param参数处理请求
}
请求体参数
对于POST请求,你可以使用@RequestBody
注解来获取请求体中的参数值。例如:
@PostMapping("/users")
public User createUser(@RequestBody User user) {
// 使用user对象处理请求
}
数据绑定与响应处理
数据绑定
Spring Boot提供了强大的数据绑定功能,可以将请求中的数据自动绑定到方法参数中。例如:
@PostMapping("/users")
public User createUser(@RequestBody User user) {
// 使用user对象处理请求
}
响应处理
Spring Boot支持多种响应类型,如JSON
、XML
等。默认情况下,Spring Boot会将响应体序列化为JSON
格式。你也可以使用@ResponseBody
注解来指定返回值类型。
@GetMapping("/users")
public List<User> getUsers() {
return users;
}
数据访问与集成
Spring Boot与数据库集成
为了实现数据库连接和数据操作,你需要在项目中引入spring-boot-starter-data-jpa
依赖,并配置数据库连接信息。
配置数据库连接
在application.properties
文件中添加数据库连接信息:
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=admin
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
创建实体类
创建一个表示数据库表的实体类,使用@Entity
注解:
package com.example.demo.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
// 构造函数、getter和setter省略
}
创建仓库接口
创建一个扩展了JpaRepository
接口的仓库接口,用于定义数据操作方法:
package com.example.demo.repository;
import com.example.demo.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
}
创建服务类
创建一个服务类来处理业务逻辑,注入仓库接口:
package com.example.demo.service;
import com.example.demo.model.User;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public User createUser(User user) {
return userRepository.save(user);
}
public User getUser(Long id) {
return userRepository.findById(id).orElse(null);
}
public List<User> getAllUsers() {
return userRepository.findAll();
}
}
创建控制器类
创建一个控制器类来处理HTTP请求,注入服务类:
package com.example.demo.controller;
import com.example.demo.model.User;
import com.example.demo.service.UserService;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping
public List<User> getUsers() {
return userService.getAllUsers();
}
@PostMapping
public User createUser(@RequestBody User user) {
return userService.createUser(user);
}
@GetMapping("/{id}")
public User getUserById(@PathVariable Long id) {
return userService.getUser(id);
}
@PutMapping("/{id}")
public User updateUser(@PathVariable Long id, @RequestBody User user) {
User existingUser = userService.getUser(id);
if (existingUser != null) {
existingUser.setName(user.getName());
existingUser.setEmail(user.getEmail());
return userService.createUser(existingUser);
}
return null;
}
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable Long id) {
userService.deleteUser(id);
}
}
运行应用
运行应用,访问http://localhost:8080/api/users
来测试用户列表的获取,访问http://localhost:8080/api/users/1
来测试根据ID获取用户,访问http://localhost:8080/api/users
并发送POST请求来创建用户。
使用JPA和Hibernate进行数据操作
JPA(Java Persistence API)和Hibernate是Spring Boot中常用的持久化框架。JPA提供了一套标准的持久化接口,而Hibernate是一个JPA实现。
JPA实体类
JPA实体类需要使用@Entity
注解标记,并定义主键字段。例如:
package com.example.demo.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
// 构造函数、getter和setter省略
}
JPA仓库接口
JPA仓库接口继承自JpaRepository
接口,定义了常用的数据操作方法。例如:
package com.example.demo.repository;
import com.example.demo.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
}
JPA服务类
服务类负责业务逻辑处理,注入仓库接口来操作数据。例如:
package com.example.demo.service;
import com.example.demo.model.User;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public User createUser(User user) {
return userRepository.save(user);
}
public User getUser(Long id) {
return userRepository.findById(id).orElse(null);
}
public List<User> getAllUsers() {
return userRepository.findAll();
}
}
JPA控制器类
控制器类处理HTTP请求,注入服务类来操作数据。例如:
package com.example.demo.controller;
import com.example.demo.model.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping
public List<User> getUsers() {
return userService.getAllUsers();
}
@PostMapping
public User createUser(@RequestBody User user) {
return userService.createUser(user);
}
@GetMapping("/{id}")
public User getUserById(@PathVariable Long id) {
return userService.getUser(id);
}
@PutMapping("/{id}")
public User updateUser(@PathVariable Long id, @RequestBody User user) {
User existingUser = userService.getUser(id);
if (existingUser != null) {
existingUser.setName(user.getName());
existingUser.setEmail(user.getEmail());
return userService.createUser(existingUser);
}
return null;
}
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable Long id) {
userService.deleteUser(id);
}
}
整合其他数据源(如Redis)
Redis是一个键值存储系统,可以作为缓存、数据库、消息队列等多种用途。Spring Boot提供了对Redis的支持,通过引入spring-boot-starter-data-redis
依赖,可以方便地使用Redis。
引入依赖
在pom.xml
或build.gradle
文件中添加spring-boot-starter-data-redis
依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
配置Redis连接
在application.properties
文件中添加Redis连接信息:
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=password
使用RedisTemplate
Spring Boot提供了RedisTemplate
模板类,用于操作Redis。例如,创建一个服务类来使用RedisTemplate
:
package com.example.demo.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
@Service
public class RedisService {
@Autowired
private RedisTemplate<String, String> redisTemplate;
public void save(String key, String value) {
redisTemplate.opsForValue().set(key, value);
}
public String get(String key) {
return redisTemplate.opsForValue().get(key);
}
}
使用控制器调用Redis服务
创建一个控制器类来调用Redis服务类的方法:
package com.example.demo.controller;
import com.example.demo.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/redis")
public class RedisController {
@Autowired
private RedisService redisService;
@PostMapping("/save")
public String save(@RequestParam String key, @RequestParam String value) {
redisService.save(key, value);
return "Saved";
}
@GetMapping("/get/{key}")
public String get(@PathVariable String key) {
return redisService.get(key);
}
}
运行应用,访问http://localhost:8080/api/redis/save?key=mykey&value=myvalue
来保存数据,访问http://localhost:8080/api/redis/get/mykey
来获取数据。
内置模板引擎Thymeleaf介绍
Thymeleaf是一个现代的服务器端Java模板引擎,支持多种模板格式,如HTML、XML、JavaScript等。Spring Boot内置了对Thymeleaf的支持。
配置依赖
在pom.xml
或build.gradle
文件中添加spring-boot-starter-thymeleaf
依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
使用Thymeleaf模板
创建一个Thymeleaf模板文件,放在src/main/resources/templates
目录下。例如,创建一个index.html
文件:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Thymeleaf Example</title>
</head>
<body>
<h1 th:text="'Hello, ' + ${name} + '!'"></h1>
<p th:text="${message}"></p>
</body>
</html>
创建控制器类
创建一个控制器类来渲染Thymeleaf模板:
package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class ThymeleafController {
@GetMapping("/")
public String index(Model model) {
model.addAttribute("name", "World");
model.addAttribute("message", "Hello from Thymeleaf!");
return "index";
}
}
运行应用,访问http://localhost:8080/
来测试Thymeleaf模板的渲染。
静态资源处理与使用
Spring Boot支持多种静态资源处理方式,如/static
、/public
、/resources
路径下的静态文件,以及/templates
路径下的Thymeleaf模板文件。
静态资源路径
默认情况下,Spring Boot会从以下路径加载静态资源:
src/main/resources/static
src/main/resources/public
src/main/resources/resources
src/main/resources/templates
例如,创建一个src/main/resources/static/css/style.css
文件:
body {
background-color: #f0f0f0;
font-family: Arial, sans-serif;
}
在Thymeleaf模板中引用静态文件:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Thymeleaf Example</title>
<link rel="stylesheet" th:href="@{/css/style.css}" />
</head>
<body>
<h1 th:text="'Hello, ' + ${name} + '!'"></h1>
<p th:text="${message}"></p>
</body>
</html>
静态资源映射
你还可以通过WebMvcConfigurer
接口来自定义静态资源路径和映射规则。
配置静态资源映射
创建一个配置类来配置静态资源路径:
package com.example.demo.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/images/**")
.addResourceLocations("classpath:/static/images/");
}
}
创建一个src/main/resources/static/images/logo.png
文件,然后在Thymeleaf模板中引用:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Thymeleaf Example</title>
<link rel="stylesheet" th:href="@{/css/style.css}" />
</head>
<body>
<h1 th:text="'Hello, ' + ${name} + '!'"></h1>
<p th:text="${message}"></p>
<img th:class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="@{/images/logo.png}" alt="Logo" />
</body>
</html>
通过Spring Boot渲染HTML页面
创建HTML页面
在src/main/resources/templates
目录下创建一个HTML页面,例如src/main/resources/templates/greeting.html
:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Greeting Page</title>
</head>
<body>
<h1 th:text="'Hello, ' + ${name} + '!'"></h1>
<p th:text="${message}"></p>
</body>
</html>
创建控制器类
创建一个控制器类来渲染HTML页面:
package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class GreetingController {
@GetMapping("/greeting")
public String greeting(Model model) {
model.addAttribute("name", "World");
model.addAttribute("message", "Hello from Thymeleaf!");
return "greeting";
}
}
运行应用,访问http://localhost:8080/greeting
来测试HTML页面的渲染。
日志记录与配置
Spring Boot提供了多种日志框架的支持,如SLF4J、Logback、Log4j等。默认情况下,Spring Boot使用Logback
作为日志框架。你可以在application.properties
或application.yml
文件中配置日志级别等信息。
配置日志级别
在application.properties
文件中配置日志级别:
logging.level.root=INFO
logging.level.org.springframework=DEBUG
配置日志文件
你还可以配置日志文件的保存路径和文件名:
logging.file.name=logs/app.log
日志格式化
你可以通过配置文件定制日志的输出格式:
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} - %msg%n
logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} - %msg%n
使用@Slf4j
注解
Spring Boot提供了@Slf4j
注解来简化日志记录的代码编写。例如:
package com.example.demo.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class GreetingController {
private static final Logger logger = LoggerFactory.getLogger(GreetingController.class);
@GetMapping("/greeting")
public String greeting(Model model) {
logger.info("Handling greeting request");
model.addAttribute("name", "World");
model.addAttribute("message", "Hello from Thymeleaf!");
return "greeting";
}
}
异常处理机制
Spring Boot提供了多种方式来处理异常,如全局异常处理、自定义异常处理等。
全局异常处理
你可以创建一个全局异常处理器来处理所有未捕获的异常:
package com.example.demo;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
@ResponseBody
public ResponseEntity<String> handleException(Exception ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
自定义异常处理
你可以为特定的异常类型创建自定义的异常处理器:
package com.example.demo;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice
public class CustomExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
@ResponseBody
public ResponseEntity<String> handleResourceNotFoundException(ResourceNotFoundException ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
}
}
自定义异常类
创建一个自定义异常类,继承RuntimeException
:
package com.example.demo;
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException(String message) {
super(message);
}
}
抛出自定义异常
在控制器类中抛出自定义异常:
package com.example.demo.controller;
import com.example.demo.ResourceNotFoundException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@GetMapping("/users/{id}")
public User getUserById(@PathVariable Long id) {
if (id == 1) {
throw new ResourceNotFoundException("User not found");
}
// 返回用户信息
}
}
运行应用,访问http://localhost:8080/users/1
来测试自定义异常的处理。
通过以上步骤,你可以创建一个简单的Spring Boot应用,并实现RESTful API、数据访问、日志和异常处理等功能。Spring Boot的简单和强大使其成为构建现代Web应用的理想选择。
共同學習,寫下你的評論
評論加載中...
作者其他優質文章