Spring Boot 备忘单
Spring Boot 备忘单
注释
Annotation | Description | Example |
---|---|---|
@SpringBootApplication | Marks a class as a Spring Boot application. Enables auto-configuration and component scanning. | @SpringBootApplication |
@RestController | Indicates that a class provides RESTful endpoints. It combines @Controller and @ResponseBody annotations. | @RestController |
@RequestMapping | Maps HTTP requests to handler methods of RESTful controllers. | @RequestMapping("/api") |
@Autowired | Injects dependencies into a Spring bean. It can be used for constructor, setter, or field injection. | @Autowired private MyService myService; |
@Component | Indicates that a class is a Spring-managed component. It is automatically detected during component scanning. | @Component |
@Repository | Marks a class as a Spring Data repository. It handles data access and persistence logic. | @Repository |
@Service | Marks a class as a service component in the business layer. It is used to separate business logic from presentation logic. | @Service |
@Configuration | Indicates that a class provides bean definitions. It is used along with @bean to define beans in Java-based configuration. | @Configuration |
@Value | Injects values from properties files or environment variables into Spring beans. | @Value("${my.property}") private String property; |
控制流程
- 初始化:Spring Boot 首先加载应用程序属性和自动配置 bean。
- 组件扫描:Spring 扫描控制器、服务和存储库等组件。
- Bean 创建:Spring 创建 Bean 并使用依赖注入解析依赖关系。
- 请求处理:传入的 HTTP 请求根据请求映射映射到控制器方法。
- 执行:控制器方法处理请求、与服务交互并返回响应。
- 响应渲染:Spring 将方法返回值转换为适当的 HTTP 响应(例如 JSON)。
推荐的文件夹结构
src
├── 主要
│ ├── java
│ │ └── com
│ │ └── 例子
│ │ ├── 控制器
│ │ │ └──MyController.java
│ │ ├── 服务
│ │ │ └──MyService.java
│ │ └── Application.java
│ └── 资源
│ ├── application.properties
│ └── 模板
│ └──index.html
└── 测试
└── java
└── com
└── 例子
└── 控制器
└── MyControllerTest.java
Spring Boot 备忘单中的错误处理
错误处理是构建健壮应用程序的一个关键方面。 Spring Boot 提供了多种优雅处理错误和异常的机制,确保流畅的用户体验。
错误类型
- 客户端错误:无效客户端请求导致的错误,例如 400 Bad Request 或 404 Not Found。
- 服务器错误:服务器端发生的错误,例如500内部服务器错误。
- 验证错误:由于输入无效或数据验证失败而导致的错误。
错误处理机制
1. 控制者建议
- @ControllerAdvice:用于在 Spring MVC 中定义全局异常处理程序的注解。
- @ExceptionHandler:用于处理控制器建议中的特定异常的注释。
- 示例:
@ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(MyException.class) public ResponseEntity<ErrorResponse> handleMyException(MyException ex) { ErrorResponse response = new ErrorResponse("My error message"); return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST); } @ExceptionHandler(Exception.class) public ResponseEntity<ErrorResponse> handleException(Exception ex) { ErrorResponse response = new ErrorResponse("Internal server error"); return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR); } }
响应实体异常处理程序
- ResponseEntityExceptionHandler:处理常见 Spring MVC 异常的基类。
- 重写:重写handleMethodArgumentNotValid、handleHttpMessageNotReadable等方法
- 示例:
@ControllerAdvice public class CustomExceptionHandler extends ResponseEntityExceptionHandler { @Override protected ResponseEntity<Object> handleMethodArgumentNotValid( MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { ErrorResponse response = new ErrorResponse("Validation failed"); return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST); } // Other overrides for handling specific exceptions
3. 错误属性
- ErrorAttributes:用于自定义错误响应内容和格式的接口。
- DefaultErrorAttributes:Spring Boot 提供的默认实现。
@Component public class CustomErrorAttributes extends DefaultErrorAttributes { @Override public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) { Map<String, Object> errorAttributes = super.getErrorAttributes(webRequest, includeStackTrace); errorAttributes.put("customAttribute", "Custom value"); return errorAttributes; } }
使用属性文件
- application.properties:存储应用程序范围的属性,例如服务器端口、数据库 URL 等
- 自定义属性文件:为不同环境定义自定义属性文件(例如application-dev.properties)。
- 访问属性:使用@Value注释或Spring的Environment API访问属性。
建筑工程
- Maven:运行 mvn clean install 来构建项目并生成可执行 JAR。
- Gradle:运行 ./gradlew build 来构建项目并生成可执行 JAR。
附加主题
- Spring Boot Starters:使用 starters 向项目添加依赖项和自动配置。
- 日志记录:使用 Logback、Log4j 或 Java Util Logging 配置日志记录。
- 错误处理:使用@ControllerAdvice实现全局异常处理。
- 测试:使用 JUnit、Mockito 和 SpringBootTest 编写单元测试和集成测试。
以上是Spring Boot 备忘单的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

公司安全软件导致部分应用无法正常运行的排查与解决方法许多公司为了保障内部网络安全,会部署安全软件。...

将姓名转换为数字以实现排序的解决方案在许多应用场景中,用户可能需要在群组中进行排序,尤其是在一个用...

系统对接中的字段映射处理在进行系统对接时,常常会遇到一个棘手的问题:如何将A系统的接口字段有效地映�...

在使用MyBatis-Plus或其他ORM框架进行数据库操作时,经常需要根据实体类的属性名构造查询条件。如果每次都手动...

在使用IntelliJIDEAUltimate版本启动Spring...

Java对象与数组的转换:深入探讨强制类型转换的风险与正确方法很多Java初学者会遇到将一个对象转换成数组的�...

电商平台SKU和SPU表设计详解本文将探讨电商平台中SKU和SPU的数据库设计问题,特别是如何处理用户自定义销售属...

Redis缓存方案如何实现产品排行榜列表的需求?在开发过程中,我们常常需要处理排行榜的需求,例如展示一个�...
