SpringBoot 与 Java Web 注解知识文库
系统整理 Java Web、Spring Boot、MyBatis、参数校验、异常处理、JSON、Lombok、JUnit5、Mockito 学习中常见注解。适合作为后续复习和项目开发时的速查文档。
相关笔记
- **MyBatis-完全指南**
- **MyBatis-Mapper映射**
- **MyBatis-进阶应用**
- **SpringBoot-测试专题**
- **JUnit5-注解体系**
- **Mockito-完全指南**
一、注解整体理解
SpringBoot / Java Web 中的注解,本质上是告诉框架:
这个类是什么角色;
这个方法处理什么请求;
这个参数从哪里来;
这个对象是否交给 Spring 管理;
这个 SQL 如何执行;
这个测试如何运行。可以按层记忆:
启动配置层:@SpringBootApplication、@Configuration、@Bean
Controller 层:@RestController、@Controller、@RequestMapping、@GetMapping、@PostMapping
参数绑定层:@RequestParam、@PathVariable、@RequestBody、@RequestHeader
Service 层:@Service、@Transactional
Mapper 层:@Mapper、@MapperScan、@Select、@Insert、@Update、@Delete、@Param
异常处理层:@RestControllerAdvice、@ControllerAdvice、@ExceptionHandler
测试层:@Test、@SpringBootTest、@WebMvcTest、@Mock、@MockBean、@InjectMocks二、SpringBoot 启动与配置类注解
1. @SpringBootApplication
SpringBoot 项目的主启动类注解。
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}它是一个组合注解,包含:
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan作用:
| 功能 | 说明 |
|---|---|
| 标记配置类 | 表示这是 SpringBoot 主配置类 |
| 开启自动配置 | 根据依赖自动配置 Spring、MVC、数据库等组件 |
| 开启组件扫描 | 默认扫描启动类所在包及其子包 |
注意:启动类最好放在项目根包下,否则子包中的 Controller、Service、Mapper 可能扫描不到。
2. @Configuration
声明当前类是配置类,相当于以前的 XML 配置文件。
@Configuration
public class WebConfig {
}常用于:
- 注册 Bean
- 配置拦截器
- 配置跨域
- 配置消息转换器
- 配置静态资源映射
3. @Bean
把方法返回值交给 Spring 容器管理。
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}适合:
- 第三方类无法直接加
@Component - 需要手动创建对象
- 测试中替换某些 Bean
4. @Primary
当同一类型存在多个 Bean 时,优先使用被 @Primary 标记的 Bean。
@Bean
@Primary
public Clock fixedClock() {
return Clock.fixed(Instant.parse("2024-01-01T00:00:00Z"), ZoneId.of("UTC"));
}常用于测试配置,例如固定系统时间。
三、Controller 层注解
Controller 层负责接收 HTTP 请求,常见于 Java Web、Spring MVC、前后端分离接口。
1. @Controller
声明传统 Spring MVC 控制器。
@Controller
public class PageController {
@RequestMapping("/index")
public String index() {
return "index";
}
}特点:
- 返回值通常是页面名称
- 适合 JSP、Thymeleaf 等服务端页面
- 如果要返回 JSON,需要配合
@ResponseBody
2. @RestController
声明 REST 风格控制器。
@RestController
public class UserController {
}等价于:
@Controller
@ResponseBody作用:类中方法默认返回 JSON、字符串等响应体数据,而不是页面。
前后端分离项目中最常用。
3. @ResponseBody
把方法返回值直接写入 HTTP 响应体。
@Controller
public class UserController {
@ResponseBody
@RequestMapping("/user")
public User getUser() {
return new User("张三", 18);
}
}如果没有 @ResponseBody,Spring MVC 可能会把返回字符串当成页面路径。
4. @RequestMapping
通用请求映射注解。
@RequestMapping("/users")
public class UserController {
}也可以写在方法上:
@RequestMapping("/list")
public List<User> list() {
return userService.list();
}常用属性:
| 属性 | 说明 |
|---|---|
value / path | 请求路径 |
method | 请求方式 |
params | 限制请求参数 |
headers | 限制请求头 |
produces | 响应数据类型 |
consumes | 请求数据类型 |
示例:
@RequestMapping(value = "/users", method = RequestMethod.GET)实际开发中更常用 @GetMapping、@PostMapping 等简化注解。
5. @GetMapping
处理 GET 请求。
@GetMapping("/users")
public List<User> list() {
return userService.list();
}适合:
- 查询列表
- 查询详情
- 搜索数据
等价于:
@RequestMapping(value = "/users", method = RequestMethod.GET)6. @PostMapping
处理 POST 请求。
@PostMapping("/users")
public void add(@RequestBody User user) {
userService.add(user);
}适合:
- 新增数据
- 提交表单
- 登录
- 上传数据
7. @PutMapping
处理 PUT 请求,通常用于完整更新资源。
@PutMapping("/users/{id}")
public void update(@PathVariable Long id, @RequestBody User user) {
userService.update(id, user);
}8. @DeleteMapping
处理 DELETE 请求,通常用于删除资源。
@DeleteMapping("/users/{id}")
public void delete(@PathVariable Long id) {
userService.delete(id);
}9. @PatchMapping
处理 PATCH 请求,通常用于局部更新。
@PatchMapping("/users/{id}/status")
public void updateStatus(@PathVariable Long id, @RequestParam String status) {
userService.updateStatus(id, status);
}四、请求参数绑定注解
这些注解用于把 HTTP 请求中的数据绑定到 Java 方法参数上。
1. @RequestParam
获取 URL 查询参数或表单参数。
@GetMapping("/users")
public List<User> list(@RequestParam String name) {
return userService.findByName(name);
}请求示例:
GET /users?name=zhangsan常用写法:
@RequestParam(required = false)
@RequestParam(defaultValue = "1")
@RequestParam("page")分页示例:
@GetMapping("/users")
public Page<User> page(
@RequestParam(defaultValue = "1") Integer page,
@RequestParam(defaultValue = "10") Integer size
) {
return userService.page(page, size);
}2. @PathVariable
获取路径变量。
@GetMapping("/users/{id}")
public User getById(@PathVariable Long id) {
return userService.getById(id);
}请求示例:
GET /users/1001如果路径变量名和参数名不同:
@GetMapping("/users/{userId}")
public User getById(@PathVariable("userId") Long id) {
return userService.getById(id);
}3. @RequestBody
接收 JSON 请求体。
@PostMapping("/users")
public void add(@RequestBody User user) {
userService.add(user);
}请求体示例:
{
"name": "张三",
"age": 18
}常用于:
- 新增
- 修改
- 登录
- 批量提交
- 前后端分离接口
注意:GET 请求一般不用 @RequestBody,POST / PUT 更常见。
4. @RequestHeader
获取请求头。
@GetMapping("/profile")
public User profile(@RequestHeader("Authorization") String token) {
return userService.getByToken(token);
}常用于:
- 获取 token
- 获取客户端信息
- 获取语言
- 获取 User-Agent
5. @CookieValue
获取 Cookie 值。
@GetMapping("/session")
public String session(@CookieValue("SESSION") String sessionId) {
return sessionId;
}五、IoC / DI 组件注解
这些注解用于把对象交给 Spring 容器管理。
1. @Component
最普通的组件注解。
@Component
public class SmsClient {
}表示这个类会被 Spring 扫描并创建对象。
2. @Service
业务层组件。
@Service
public class UserService {
}用于 Service 层,表达这里写业务逻辑。
3. @Repository
数据访问层组件。
@Repository
public class UserRepository {
}常用于 DAO 层。
MyBatis 项目中更常见的是 @Mapper。
4. @Autowired
自动注入 Bean。
@Autowired
private UserService userService;Spring 会从容器中找到一个 UserService 类型的 Bean,然后赋值给字段。
可以注入到:
| 位置 | 示例 |
|---|---|
| 字段 | @Autowired private UserService userService; |
| 构造方法 | public UserController(UserService userService) |
| setter 方法 | @Autowired public void setUserService(...) |
| 测试方法参数 | void test(@Autowired Clock clock) |
推荐构造器注入:
@RestController
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
}5. @Qualifier
当同一类型有多个 Bean 时,指定注入哪个。
@Autowired
@Qualifier("smsMessageService")
private MessageService messageService;6. @Value
读取配置文件中的值。
@Value("${server.port}")
private Integer port;也可以设置默认值:
@Value("${app.name:demo}")
private String appName;六、配置绑定注解
1. @ConfigurationProperties
把配置文件中的一组配置绑定到 Java 对象。
@ConfigurationProperties(prefix = "aliyun.oss")
@Component
public class OssProperties {
private String endpoint;
private String accessKeyId;
private String accessKeySecret;
}对应配置:
aliyun:
oss:
endpoint: xxx
access-key-id: xxx
access-key-secret: xxx适合多个配置项的统一管理。
2. @EnableConfigurationProperties
开启某个配置属性类。
@EnableConfigurationProperties(OssProperties.class)
@Configuration
public class OssConfig {
}如果属性类已经加了 @Component,一般可以不用它。
七、MyBatis 相关注解
主要来自 **MyBatis-Mapper映射** 和 **MyBatis-进阶应用**。
1. @Mapper
标记 MyBatis Mapper 接口。
@Mapper
public interface UserMapper {
User selectById(Long id);
}作用:
- 让 MyBatis 为接口生成代理对象
- 让 Spring 可以注入这个 Mapper
- 常用于 DAO / Mapper 层
2. @MapperScan
批量扫描 Mapper 接口。
@SpringBootApplication
@MapperScan("com.example.mapper")
public class Application {
}这样每个 Mapper 接口就不用单独写 @Mapper。
3. @Select
直接在 Mapper 方法上写查询 SQL。
@Select("SELECT * FROM users WHERE id = #{id}")
User selectById(Long id);适合简单查询。
4. @Insert
直接写插入 SQL。
@Insert("INSERT INTO users (user_name, email) VALUES (#{name}, #{email})")
int insert(User user);5. @Update
直接写更新 SQL。
@Update("UPDATE users SET user_name = #{name} WHERE id = #{id}")
int update(User user);6. @Delete
直接写删除 SQL。
@Delete("DELETE FROM users WHERE id = #{id}")
int deleteById(Long id);7. @Options
配置 SQL 执行选项,常见于获取自增主键。
@Insert("INSERT INTO users (user_name, email) VALUES (#{name}, #{email})")
@Options(useGeneratedKeys = true, keyProperty = "id")
int insert(User user);作用:插入成功后,把数据库生成的主键回填到 user.id。
8. @Param
给 Mapper 方法参数起名字。
@Select("SELECT * FROM users WHERE name = #{name} AND age = #{age}")
List<User> selectByNameAndAge(@Param("name") String name,
@Param("age") Integer age);多个参数时强烈建议使用 @Param。
否则 MyBatis 可能只能用 param1、param2 或 arg0、arg1 访问参数。
9. @Results
定义结果映射规则。
@Results(id = "UserResult", value = {
@Result(column = "id", property = "id"),
@Result(column = "user_name", property = "name")
})
@Select("SELECT * FROM users WHERE id = #{id}")
User selectById(Long id);解决数据库列名和 Java 属性名不一致的问题。
10. @Result
单个字段映射。
@Result(column = "user_name", property = "name")含义:
数据库 user_name 列 → Java 对象 name 属性11. @One
一对一关联查询。
@Result(column = "user_id", property = "user",
one = @One(select = "com.example.mapper.UserMapper.selectById"))表示一个订单对应一个用户。
12. @Many
一对多关联查询。
@Result(property = "orders",
many = @Many(select = "com.example.mapper.OrderMapper.selectByUserId"))表示一个用户对应多个订单。
13. @SelectProvider
动态 SQL 提供者。
@SelectProvider(type = UserSqlProvider.class, method = "search")
List<User> search(UserQuery query);当 SQL 比较复杂、需要动态拼接时,可以把 SQL 构建逻辑放到单独类中。
14. @Alias
MyBatis 类型别名。
@Alias("user")
public class User {
}XML 中可以写:
resultType="user"而不是完整类名。
15. @MappedTypes
自定义 TypeHandler 时指定处理的 Java 类型。
@MappedTypes(LocalDateTime.class)
public class LocalDateTimeTypeHandler extends BaseTypeHandler<LocalDateTime> {
}16. @MappedJdbcTypes
自定义 TypeHandler 时指定处理的 JDBC 类型。
@MappedJdbcTypes(JdbcType.TIMESTAMP)
public class LocalDateTimeTypeHandler extends BaseTypeHandler<LocalDateTime> {
}17. @Intercepts / @Signature
MyBatis 插件拦截器相关注解。
@Intercepts({
@Signature(
type = Executor.class,
method = "query",
args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}
)
})
public class CustomInterceptor implements Interceptor {
}常用于:
- 分页插件
- SQL 日志
- 性能监控
- 权限过滤
- SQL 执行拦截
八、事务相关注解
@Transactional
开启事务。
@Transactional
public void transfer(Long fromId, Long toId, BigDecimal amount) {
accountMapper.minus(fromId, amount);
accountMapper.add(toId, amount);
}作用:
方法执行成功 → 提交事务
方法抛出运行时异常 → 回滚事务常用在 Service 层。
测试中也常用:
@SpringBootTest
@Transactional
class UserServiceTest {
}测试中的 @Transactional 通常会让每个测试方法执行后自动回滚,保证测试数据干净。
注意点:
| 问题 | 说明 |
|---|---|
| 默认只回滚运行时异常 | RuntimeException、Error |
| 同类内部方法调用可能不生效 | 因为绕过 Spring 代理 |
| 一般加在 Service 层 | 不建议写在 Controller 层 |
查询方法可加 readOnly = true | 语义更清楚 |
普通异常也回滚:
@Transactional(rollbackFor = Exception.class)九、参数校验相关注解
Java Web 表单提交、JSON 请求经常要做参数校验。
1. @Valid
触发对象校验。
@PostMapping("/users")
public void add(@RequestBody @Valid UserDTO userDTO) {
}2. @Validated
Spring 提供的校验注解,支持分组校验。
@PostMapping("/users")
public void add(@RequestBody @Validated UserDTO userDTO) {
}3. @NotNull
字段不能为 null。
@NotNull
private Long id;4. @NotBlank
字符串不能为 null,也不能为空白字符串。
@NotBlank
private String username;适合用户名、标题、内容。
5. @NotEmpty
集合或字符串不能为空。
@NotEmpty
private List<Long> ids;6. @Size
限制长度或集合大小。
@Size(min = 2, max = 20)
private String username;7. @Min / @Max
限制数字范围。
@Min(1)
@Max(100)
private Integer age;8. @Email
校验邮箱格式。
@Email
private String email;9. @Pattern
使用正则表达式校验。
@Pattern(regexp = "^1[3-9]\\d{9}$")
private String phone;十、异常处理相关注解
1. @ControllerAdvice
全局 Controller 增强。
@ControllerAdvice
public class GlobalExceptionHandler {
}常用于:
- 全局异常处理
- 全局数据绑定
- 全局响应处理
2. @RestControllerAdvice
REST 风格全局异常处理。
@RestControllerAdvice
public class GlobalExceptionHandler {
}等价于:
@ControllerAdvice + @ResponseBody前后端分离项目更常用。
3. @ExceptionHandler
指定处理某类异常。
@ExceptionHandler(Exception.class)
public Result handleException(Exception e) {
return Result.error(e.getMessage());
}完整示例:
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(BusinessException.class)
public Result handleBusinessException(BusinessException e) {
return Result.error(e.getMessage());
}
@ExceptionHandler(Exception.class)
public Result handleException(Exception e) {
return Result.error("系统异常");
}
}十一、跨域与 Web 配置相关注解
1. @CrossOrigin
允许跨域请求。
@CrossOrigin
@RestController
@RequestMapping("/users")
public class UserController {
}也可以指定来源:
@CrossOrigin(origins = "http://localhost:5173")前后端分离时常见。
2. @EnableWebMvc
开启 Spring MVC 完全自定义配置。
@EnableWebMvc
@Configuration
public class WebConfig {
}注意:SpringBoot 中一般不建议随便加 @EnableWebMvc,因为它会接管部分自动配置。
十二、JSON 序列化相关注解
这些注解常见于接口返回 JSON 时。
1. @JsonFormat
格式化日期。
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private LocalDateTime createTime;2. @JsonIgnore
返回 JSON 时忽略某个字段。
@JsonIgnore
private String password;3. @JsonProperty
指定 JSON 字段名。
@JsonProperty("user_name")
private String userName;十三、Lombok 常见注解
Java Web / SpringBoot 学习项目中经常会遇到 Lombok。
1. @Data
自动生成:
- getter
- setter
- toString
- equals
- hashCode
@Data
public class User {
private Long id;
private String name;
}2. @Getter / @Setter
只生成 getter / setter。
@Getter
@Setter
public class User {
}3. @NoArgsConstructor
生成无参构造器。
@NoArgsConstructor
public class User {
}4. @AllArgsConstructor
生成全参构造器。
@AllArgsConstructor
public class User {
}5. @Builder
使用建造者模式创建对象。
@Builder
public class User {
private Long id;
private String name;
}调用:
User user = User.builder()
.id(1L)
.name("张三")
.build();6. @Slf4j
生成日志对象。
@Slf4j
@Service
public class UserService {
public void test() {
log.info("执行用户服务");
}
}十四、JUnit 5 测试注解
主要来自 **JUnit5-注解体系**。
1. @Test
标记测试方法。
@Test
void testAdd() {
assertEquals(2, 1 + 1);
}2. @DisplayName
给测试类或测试方法起一个可读名称。
@DisplayName("用户服务测试")
class UserServiceTest {
}3. @BeforeEach
每个测试方法执行前运行。
@BeforeEach
void setUp() {
user = new User();
}4. @AfterEach
每个测试方法执行后运行。
@AfterEach
void tearDown() {
}5. @BeforeAll
所有测试方法执行前运行一次。
@BeforeAll
static void initAll() {
}默认要求方法是 static。
6. @AfterAll
所有测试方法执行后运行一次。
@AfterAll
static void cleanAll() {
}7. @Nested
嵌套测试类,用于组织测试结构。
@Nested
@DisplayName("新增用户")
class AddUserTest {
}8. @Disabled
禁用测试。
@Disabled("暂时跳过")
@Test
void testOldFeature() {
}9. @Tag
给测试打标签。
@Tag("slow")
@Test
void integrationTest() {
}10. @RepeatedTest
重复执行测试。
@RepeatedTest(5)
void repeatTest() {
}11. @ParameterizedTest
参数化测试。
@ParameterizedTest
@ValueSource(strings = {"a", "b", "c"})
void testWithParams(String value) {
}12. 参数源注解
| 注解 | 作用 |
|---|---|
@ValueSource | 简单值来源 |
@CsvSource | CSV 行内数据 |
@CsvFileSource | CSV 文件数据 |
@MethodSource | 方法提供参数 |
@EnumSource | 枚举参数 |
@NullSource | 提供 null |
@EmptySource | 提供空字符串/空集合 |
@NullAndEmptySource | 提供 null 和 empty |
@ArgumentsSource | 自定义参数源 |
13. 条件执行注解
| 注解 | 作用 |
|---|---|
@EnabledOnOs | 指定操作系统启用 |
@DisabledOnOs | 指定操作系统禁用 |
@EnabledOnJre | 指定 JRE 启用 |
@DisabledOnJre | 指定 JRE 禁用 |
@EnabledIfSystemProperty | 根据系统属性启用 |
@EnabledIfEnvironmentVariable | 根据环境变量启用 |
@EnabledIf | 自定义条件启用 |
@DisabledIf | 自定义条件禁用 |
14. @TestInstance
设置测试实例生命周期。
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class UserServiceTest {
}如果使用 PER_CLASS,@BeforeAll 可以不是 static。
十五、SpringBoot 测试注解
主要来自 **SpringBoot-测试专题**。
1. @SpringBootTest
加载完整 SpringBoot 应用上下文。
@SpringBootTest
class UserServiceTest {
}适合:
- 集成测试
- Service + Mapper 联合测试
- 需要完整 Spring 容器的测试
常见写法:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)表示启动随机端口。
2. @WebMvcTest
只测试 Web 层。
@WebMvcTest(UserController.class)
class UserControllerTest {
}特点:
- 只加载 Controller 相关 Bean
- 不加载完整 Service、Mapper
- 通常配合
@MockBean
示例:
@WebMvcTest(UserController.class)
class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private UserService userService;
}3. @DataJpaTest
只测试 JPA 数据访问层。
@DataJpaTest
class UserRepositoryTest {
}特点:
- 只加载 Repository 相关组件
- 默认使用内存数据库
- 默认测试后回滚
4. @JsonTest
只测试 JSON 序列化与反序列化。
@JsonTest
class UserJsonTest {
}用于验证:
- 日期格式
- JSON 字段名
- 忽略字段
- 对象转 JSON 是否正确
5. @AutoConfigureMockMvc
自动配置 MockMvc。
@SpringBootTest
@AutoConfigureMockMvc
class UserControllerIntegrationTest {
@Autowired
private MockMvc mockMvc;
}适合在完整 SpringBoot 环境下测试接口。
6. @AutoConfigureTestDatabase
配置测试数据库替换策略。
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
class UserRepositoryTest {
}表示不替换为内存数据库,而使用真实数据库。
7. @TestConfiguration
定义测试专用配置。
@TestConfiguration
static class TestConfig {
@Bean
@Primary
public Clock clock() {
return Clock.fixed(Instant.parse("2024-01-01T00:00:00Z"), ZoneId.of("UTC"));
}
}适合:
- 替换真实 Bean
- 提供测试专用 Bean
- 固定时间
- Mock 第三方服务
8. @DynamicPropertySource
动态注册测试配置。
@DynamicPropertySource
static void properties(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", postgres::getJdbcUrl);
}常用于 Testcontainers 中动态注入数据库地址。
9. @Testcontainers
启用 Testcontainers。
@Testcontainers
@SpringBootTest
class IntegrationTest {
}10. @Container
声明一个测试容器。
@Container
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:15");用于启动真实数据库、Redis、Kafka 等容器。
十六、Mockito 注解
主要来自 **Mockito-完全指南**。
1. @ExtendWith(MockitoExtension.class)
让 JUnit 5 启用 Mockito 扩展。
@ExtendWith(MockitoExtension.class)
class UserServiceTest {
}如果使用 @Mock、@InjectMocks,通常要加它。
2. @Mock
创建 Mock 对象。
@Mock
private UserRepository userRepository;Mock 对象的方法默认不会真的执行,可以用 when(...).thenReturn(...) 设置返回值。
3. @InjectMocks
把 Mock 对象注入到被测试对象中。
@InjectMocks
private UserService userService;常见组合:
@Mock
private UserMapper userMapper;
@InjectMocks
private UserService userService;表示测试 UserService,但它依赖的 UserMapper 是假的。
4. @Spy
部分 Mock。
@Spy
private List<String> list = new ArrayList<>();Spy 默认调用真实方法,但可以对部分方法打桩。
5. @Captor
参数捕获器。
@Captor
private ArgumentCaptor<User> userCaptor;用于验证方法调用时传入的参数。
6. @MockBean
SpringBoot 测试中替换 Spring 容器里的 Bean。
@SpringBootTest
class UserControllerTest {
@MockBean
private UserService userService;
}@Mock 和 @MockBean 的区别:
| 注解 | 所属 | 是否进入 Spring 容器 | 常用场景 |
|---|---|---|---|
@Mock | Mockito | 否 | 普通单元测试 |
@MockBean | SpringBoot Test | 是 | SpringBoot 集成测试 |
@InjectMocks | Mockito | 否 | 把 Mock 注入被测对象 |
@Autowired | Spring | 是 | 从 Spring 容器取 Bean |
7. @MockitoSettings
配置 Mockito 行为。
@MockitoSettings(strictness = Strictness.LENIENT)常用于关闭严格未使用打桩检查。
十七、Java 原生注解
这些不是 SpringBoot 专属,但 Java 学习中经常遇到。
1. @Override
表示重写父类或接口方法。
@Override
public String toString() {
return "User";
}作用:
- 提高可读性
- 编译器检查是否真的重写成功
2. @FunctionalInterface
声明函数式接口。
@FunctionalInterface
public interface MyFunction {
void apply();
}函数式接口只能有一个抽象方法,常用于 Lambda 表达式。
3. @Deprecated
标记过时 API。
@Deprecated
public void oldMethod() {
}表示不推荐继续使用。
4. @SuppressWarnings
抑制编译器警告。
@SuppressWarnings("unchecked")
public void test() {
}十八、常见开发组合模板
1. SpringBoot 启动类 + MyBatis
@SpringBootApplication
@MapperScan("com.example.mapper")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}2. Controller 接收请求
@RestController
@RequestMapping("/users")
public class UserController {
@GetMapping("/{id}")
public User getById(@PathVariable Long id) {
return userService.getById(id);
}
@PostMapping
public void add(@RequestBody User user) {
userService.add(user);
}
}3. Service 处理业务和事务
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
@Transactional
public void add(User user) {
userMapper.insert(user);
}
}4. Mapper 操作数据库
@Mapper
public interface UserMapper {
@Select("SELECT * FROM users WHERE id = #{id}")
User selectById(Long id);
@Insert("INSERT INTO users(name, age) VALUES(#{name}, #{age})")
int insert(User user);
}5. SpringBoot 接口测试
@SpringBootTest
@AutoConfigureMockMvc
class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void testGetUser() throws Exception {
mockMvc.perform(get("/users/1"))
.andExpect(status().isOk());
}
}十九、注解速查总表
| 分类 | 常见注解 | 作用 |
|---|---|---|
| 启动配置 | @SpringBootApplication | SpringBoot 启动类 |
| 启动配置 | @Configuration | 配置类 |
| 启动配置 | @Bean | 注册 Bean |
| 启动配置 | @Primary | 优先注入 |
| Web 控制层 | @Controller | 页面控制器 |
| Web 控制层 | @RestController | REST 控制器 |
| Web 控制层 | @ResponseBody | 返回响应体 |
| 请求映射 | @RequestMapping | 通用请求映射 |
| 请求映射 | @GetMapping | GET 请求 |
| 请求映射 | @PostMapping | POST 请求 |
| 请求映射 | @PutMapping | PUT 请求 |
| 请求映射 | @DeleteMapping | DELETE 请求 |
| 请求映射 | @PatchMapping | PATCH 请求 |
| 参数绑定 | @RequestParam | 查询参数 / 表单参数 |
| 参数绑定 | @PathVariable | 路径变量 |
| 参数绑定 | @RequestBody | JSON 请求体 |
| 参数绑定 | @RequestHeader | 请求头 |
| 参数绑定 | @CookieValue | Cookie |
| 组件注册 | @Component | 普通组件 |
| 组件注册 | @Service | 业务层组件 |
| 组件注册 | @Repository | DAO 层组件 |
| 依赖注入 | @Autowired | 自动注入 |
| 依赖注入 | @Qualifier | 指定 Bean 名称 |
| 配置读取 | @Value | 读取单个配置 |
| 配置读取 | @ConfigurationProperties | 绑定一组配置 |
| MyBatis | @Mapper | Mapper 接口 |
| MyBatis | @MapperScan | 批量扫描 Mapper |
| MyBatis | @Select | 查询 SQL |
| MyBatis | @Insert | 插入 SQL |
| MyBatis | @Update | 更新 SQL |
| MyBatis | @Delete | 删除 SQL |
| MyBatis | @Param | 参数命名 |
| MyBatis | @Results | 结果映射集合 |
| MyBatis | @Result | 单个字段映射 |
| MyBatis | @One | 一对一关联 |
| MyBatis | @Many | 一对多关联 |
| MyBatis | @Options | SQL 执行选项 |
| MyBatis | @SelectProvider | 动态 SQL |
| 事务 | @Transactional | 开启事务 |
| 参数校验 | @Valid | 启用校验 |
| 参数校验 | @Validated | Spring 校验 / 分组校验 |
| 参数校验 | @NotNull | 不能为 null |
| 参数校验 | @NotBlank | 字符串不能为空白 |
| 参数校验 | @NotEmpty | 字符串或集合不能为空 |
| 参数校验 | @Size | 限制长度 |
| 参数校验 | @Email | 邮箱格式 |
| 异常处理 | @RestControllerAdvice | REST 全局异常处理 |
| 异常处理 | @ControllerAdvice | 全局 Controller 增强 |
| 异常处理 | @ExceptionHandler | 处理指定异常 |
| JSON | @JsonFormat | 日期格式化 |
| JSON | @JsonIgnore | 忽略字段 |
| JSON | @JsonProperty | 指定 JSON 字段名 |
| Lombok | @Data | getter/setter/toString 等 |
| Lombok | @Getter | getter |
| Lombok | @Setter | setter |
| Lombok | @NoArgsConstructor | 无参构造 |
| Lombok | @AllArgsConstructor | 全参构造 |
| Lombok | @Builder | 建造者模式 |
| Lombok | @Slf4j | 日志对象 |
| JUnit5 | @Test | 测试方法 |
| JUnit5 | @DisplayName | 测试显示名 |
| JUnit5 | @BeforeEach | 每个测试前执行 |
| JUnit5 | @AfterEach | 每个测试后执行 |
| JUnit5 | @BeforeAll | 所有测试前执行 |
| JUnit5 | @AfterAll | 所有测试后执行 |
| JUnit5 | @Nested | 嵌套测试 |
| JUnit5 | @Disabled | 禁用测试 |
| SpringBoot 测试 | @SpringBootTest | 完整上下文测试 |
| SpringBoot 测试 | @WebMvcTest | Web 层测试 |
| SpringBoot 测试 | @DataJpaTest | JPA 层测试 |
| SpringBoot 测试 | @AutoConfigureMockMvc | 自动配置 MockMvc |
| Mockito | @Mock | 创建 Mock 对象 |
| Mockito | @InjectMocks | 注入 Mock 到被测类 |
| Mockito | @Spy | 部分 Mock |
| Mockito | @Captor | 参数捕获器 |
| SpringBoot Mock | @MockBean | 替换 Spring Bean |
| Java 原生 | @Override | 重写方法 |
| Java 原生 | @FunctionalInterface | 函数式接口 |
| Java 原生 | @Deprecated | 标记过时 |
| Java 原生 | @SuppressWarnings | 抑制警告 |
二十、最终记忆口诀
启动看 Application,配置看 Bean;
接口看 Controller,请求看 Mapping;
参数看 Param、Path、Body;
业务看 Service,事务看 Transactional;
数据库看 Mapper,SQL 看 Select/Insert/Update/Delete;
异常看 Advice,校验看 Valid;
测试看 Test,Mock 看 MockBean。#标签 #Java #JavaWeb #SpringBoot #注解 #MyBatis #JUnit5 #Mockito #后端开发 #知识文库