在 Spring Boot Web 后端开发中,注解(Annotation)是核心,它们极大简化了配置、依赖管理、请求映射、数据持久化等。本文将按照功能分类,详细列出常用注解的作用、使用方式、典型场景,并附带简明代码示例,帮助你全面掌握并灵活运用。

文章目录
-
- [1. 核心启动与配置注解](#1. 核心启动与配置注解)
- [2. 控制器与请求映射注解](#2. 控制器与请求映射注解)
- [3. 依赖注入与组件注册注解](#3. 依赖注入与组件注册注解)
- [4. 数据访问(JPA / Spring Data)注解](#4. 数据访问(JPA / Spring Data)注解)
- [5. 事务管理注解](#5. 事务管理注解)
- [6. 缓存注解](#6. 缓存注解)
- [7. 异步与定时任务注解](#7. 异步与定时任务注解)
- [8. 异常处理与控制器增强](#8. 异常处理与控制器增强)
- [9. 跨域支持注解](#9. 跨域支持注解)
- [10. 条件化配置注解(自动配置相关)](#10. 条件化配置注解(自动配置相关))
- [11. 测试注解](#11. 测试注解)
- [12. Lombok 常用注解(简化代码)](#12. Lombok 常用注解(简化代码))
- [13. Spring Security 常用注解](#13. Spring Security 常用注解)
- [14. 其他常用注解](#14. 其他常用注解)

1. 核心启动与配置注解
| 注解 | 作用 | 用法 | 场景 | 代码举例 |
|---|---|---|---|---|
@SpringBootApplication |
标记主启动类,组合了 @Configuration、@EnableAutoConfiguration、@ComponentScan。 |
加在启动类上。 | Spring Boot 应用的入口。 | java @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } |
@Configuration |
声明一个类为配置类,可包含 @Bean 方法。 |
加在类上。 | 定义额外的配置 Bean。 | java @Configuration public class AppConfig { @Bean public MyService myService() { return new MyService(); } } |
@EnableAutoConfiguration |
开启 Spring Boot 自动配置,根据依赖自动配置 Bean。 | 通常由 @SpringBootApplication 组合,也可单独使用。 |
自动配置场景。 | 一般不单独使用,已包含在 @SpringBootApplication 中。 |
@ComponentScan |
定义组件扫描路径,默认扫描当前包及其子包。 | 加在配置类上,可指定 basePackages。 |
扫描 @Component、@Service 等注解的类。 |
java @Configuration @ComponentScan(basePackages = "com.example.service") public class AppConfig {} |
@PropertySource |
指定属性文件加载到 Spring Environment。 | 加在配置类上,指定文件位置。 | 加载自定义配置文件。 | java @Configuration @PropertySource("classpath:custom.properties") public class AppConfig { @Value("${my.property}") private String myProp; } |
@Value |
注入配置文件中的属性值。 | 加在字段、方法参数或方法上。 | 从 application.properties 或自定义配置中取值。 |
java @Value("${server.port}") private int port; |
@ConfigurationProperties |
将配置文件中的属性绑定到 Java Bean 上。 | 加在类上,需配合 @EnableConfigurationProperties 或 @Component 使用。 |
批量绑定配置属性。 | java @Component @ConfigurationProperties(prefix = "app") public class AppProperties { private String name; private String version; // getter/setter } |
@Import |
导入一个或多个配置类。 | 加在配置类上。 | 组合多个配置类。 | java @Configuration @Import(DatabaseConfig.class) public class AppConfig {} |
@ImportResource |
导入 XML 配置文件。 | 加在配置类上,指定 XML 路径。 | 整合旧版 XML 配置。 | java @Configuration @ImportResource("classpath:old-config.xml") public class AppConfig {} |
2. 控制器与请求映射注解
| 注解 | 作用 | 用法 | 场景 | 代码举例 |
|---|---|---|---|---|
@Controller |
标记一个类为 Spring MVC 控制器,通常返回视图(如 Thymeleaf 模板)。 | 加在类上。 | 传统 MVC 应用,返回页面。 | java @Controller public class HomeController { @GetMapping("/") public String home(Model model) { model.addAttribute("msg", "Hello"); return "home"; } } |
@RestController |
组合 @Controller + @ResponseBody,方法返回值直接作为 HTTP 响应体(JSON/XML)。 |
加在类上。 | RESTful API 开发。 | java @RestController @RequestMapping("/api/users") public class UserController { @GetMapping("/{id}") public User getUser(@PathVariable Long id) { return userService.findById(id); } } |
@RequestMapping |
映射 HTTP 请求到控制器方法,可配置路径、方法、参数等。 | 类或方法上。 | 通用请求映射。 | java @RestController @RequestMapping("/api") public class ApiController { @RequestMapping(value = "/hello", method = RequestMethod.GET) public String hello() { return "Hello"; } } |
@GetMapping |
组合 @RequestMapping(method = GET)。 |
方法上。 | 处理 GET 请求。 | java @GetMapping("/users") public List<User> list() { return userService.findAll(); } |
@PostMapping |
组合 @RequestMapping(method = POST)。 |
方法上。 | 处理 POST 请求(创建资源)。 | java @PostMapping("/users") public User create(@RequestBody User user) { return userService.save(user); } |
@PutMapping |
组合 @RequestMapping(method = PUT)。 |
方法上。 | 处理 PUT 请求(全量更新)。 | java @PutMapping("/users/{id}") public User update(@PathVariable Long id, @RequestBody User user) { return userService.update(id, user); } |
@DeleteMapping |
组合 @RequestMapping(method = DELETE)。 |
方法上。 | 处理 DELETE 请求。 | java @DeleteMapping("/users/{id}") public void delete(@PathVariable Long id) { userService.delete(id); } |
@PatchMapping |
组合 @RequestMapping(method = PATCH)。 |
方法上。 | 处理 PATCH 请求(部分更新)。 | java @PatchMapping("/users/{id}") public User partialUpdate(@PathVariable Long id, @RequestBody Map<String, Object> updates) { return userService.partialUpdate(id, updates); } |
@ResponseBody |
将方法返回值直接写入 HTTP 响应体(通常用于返回 JSON/XML)。 | 方法上,或类上结合 @Controller。 |
控制器方法返回 JSON 数据。 | java @Controller public class DataController { @GetMapping("/data") @ResponseBody public Map<String, Object> getData() { return Map.of("key", "value"); } } |
@RequestBody |
将 HTTP 请求体绑定到方法参数(自动反序列化 JSON/XML)。 | 方法参数上。 | 接收 POST/PUT 请求中的 JSON 数据。 | java @PostMapping("/users") public User create(@RequestBody User user) { return userService.save(user); } |
@RequestParam |
将请求参数绑定到方法参数。 | 方法参数上,可设置 required、defaultValue。 | 获取 URL 中的查询参数。 | java @GetMapping("/users") public List<User> list(@RequestParam(defaultValue = "0") int page) { return userService.findByPage(page); } |
@PathVariable |
将 URL 模板变量绑定到方法参数。 | 方法参数上。 | 获取 RESTful URL 中的路径变量。 | java @GetMapping("/users/{id}") public User get(@PathVariable Long id) { return userService.findById(id); } |
@RequestHeader |
将请求头信息绑定到方法参数。 | 方法参数上。 | 获取请求头,如 Token、User-Agent。 | java @GetMapping("/info") public String getInfo(@RequestHeader("User-Agent") String userAgent) { return userAgent; } |
@CookieValue |
将 Cookie 值绑定到方法参数。 | 方法参数上。 | 获取 Cookie 中的值。 | java @GetMapping("/") public String readCookie(@CookieValue(value = "sessionId", defaultValue = "") String sessionId) { return sessionId; } |
@ModelAttribute |
将请求参数绑定到 Model 对象,或在方法执行前添加模型属性。 | 方法参数或方法上。 | 表单提交绑定对象,或为所有请求添加公共数据。 | java @PostMapping("/register") public String register(@ModelAttribute User user) { userService.save(user); return "success"; } |
@SessionAttributes |
将指定的模型属性存储到 HTTP 会话中。 | 类上。 | 跨请求保持模型属性(如购物车)。 | java @Controller @SessionAttributes("cart") public class CartController { @ModelAttribute("cart") public Cart createCart() { return new Cart(); } } |
@SessionAttribute |
从会话中获取指定的属性。 | 方法参数上。 | 获取会话中已存在的属性。 | java @GetMapping("/cart") public String viewCart(@SessionAttribute Cart cart) { // 使用 cart return "cartView"; } |
@RequestAttribute |
从请求中获取指定的属性(通常由过滤器或拦截器设置)。 | 方法参数上。 | 获取请求级别的属性。 | java @GetMapping("/profile") public String profile(@RequestAttribute("userId") Long userId) { return "User ID: " + userId; } |
3. 依赖注入与组件注册注解
| 注解 | 作用 | 用法 | 场景 | 代码举例 |
|---|---|---|---|---|
@Component |
将一个类标记为 Spring 管理的通用组件。 | 加在类上。 | 任意层组件,Spring 会自动扫描并注册为 Bean。 | java @Component public class MyComponent { public void doWork() { // ... } } |
@Service |
标注业务逻辑层组件,是 @Component 的特化。 |
加在类上。 | Service 层实现类。 | java @Service public class UserService { public User findById(Long id) { // ... } } |
@Repository |
标注数据访问层组件,Spring 会自动转换持久层异常。 | 加在类上。 | DAO 层实现类(如使用 JPA、MyBatis)。 | java @Repository public class UserRepository { public User findById(Long id) { // ... } } |
@Controller |
标注控制器层组件。 | 加在类上。 | MVC 控制器。 | 已在控制器部分介绍。 |
@Autowired |
按类型自动装配依赖。可标注在构造器、方法、参数、字段上。 | 字段、构造器、setter 方法上。 | 注入依赖 Bean。 | java @Service public class UserService { @Autowired private UserRepository userRepository; } |
@Qualifier |
与 @Autowired 配合,指定按名称装配。 |
与 @Autowired 一起使用。 |
当同一类型有多个 Bean 时,指定具体 Bean 名称。 | java @Autowired @Qualifier("userJdbcRepository") private UserRepository userRepository; |
@Primary |
当存在多个相同类型的 Bean 时,优先注入被 @Primary 标注的 Bean。 |
加在 Bean 类或 @Bean 方法上。 |
确定首选 Bean。 | java @Bean @Primary public DataSource primaryDataSource() { ... } |
@Resource |
Java 标准注解,默认按名称装配,名称可通过 name 属性指定。 |
字段或 setter 方法上。 | 按名称注入,避免类型歧义。 | java @Resource(name = "userRepository") private UserRepository userRepository; |
@Inject |
Java 标准注解(JSR-330),等同于 @Autowired。 |
字段、构造器、方法上。 | 与 @Autowired 类似,需引入 javax.inject 包。 |
java @Inject private UserService userService; |
@Named |
Java 标准注解,类似 @Component,用于命名组件。 |
加在类上。 | 与 @Inject 配合,指定 Bean 名称。 |
java @Named("userService") public class UserService { ... } |
@Lazy |
延迟初始化 Bean,直到第一次使用才创建。 | 加在类或 @Bean 方法上,也可用于 @Autowired 字段。 |
优化启动时间,或避免循环依赖。 | java @Lazy @Component public class LazyBean { ... } |
@Scope |
定义 Bean 的作用域(如 singleton、prototype、request、session)。 | 加在类或 @Bean 方法上。 |
控制 Bean 的生命周期。 | java @Component @Scope("prototype") public class PrototypeBean { ... } |
@PostConstruct |
标注在初始化方法上,在依赖注入后执行。 | 加在方法上。 | Bean 初始化后的自定义逻辑。 | java @Component public class InitBean { @PostConstruct public void init() { System.out.println("Bean initialized"); } } |
@PreDestroy |
标注在销毁方法上,在 Bean 销毁前执行。 | 加在方法上。 | 释放资源等清理操作。 | java @PreDestroy public void cleanup() { System.out.println("Bean destroyed"); } |
4. 数据访问(JPA / Spring Data)注解
| 注解 | 作用 | 用法 | 场景 | 代码举例 |
|---|---|---|---|---|
@Entity |
标记一个类为 JPA 实体类。 | 加在类上。 | 定义与数据库表映射的实体。 | java @Entity @Table(name = "users") public class User { @Id @GeneratedValue private Long id; private String name; // getter/setter } |
@Table |
指定实体对应的数据库表名。 | 加在类上。 | 自定义表名、schema 等。 | 见上例。 |
@Id |
标记主键字段。 | 加在字段上。 | 标识实体主键。 | 见上例。 |
@GeneratedValue |
配置主键生成策略。 | 加在主键字段上。 | 指定主键自动生成方式(如自增、序列)。 | 见上例。 |
@Column |
配置字段与数据库列的映射(列名、是否可为空、长度等)。 | 加在字段上。 | 精确控制列属性。 | java @Column(name = "user_name", nullable = false, length = 50) private String name; |
@Transient |
标记字段不持久化到数据库。 | 加在字段上。 | 忽略某个字段(如计算属性)。 | java @Transient private int age; // 不存入数据库 |
@Temporal |
设置日期时间精度(DATE、TIME、TIMESTAMP)。 | 加在 java.util.Date 或 java.util.Calendar 字段上。 |
精确映射日期类型。 | java @Temporal(TemporalType.TIMESTAMP) private Date createdAt; |
@Enumerated |
枚举类型映射到数据库的方式(ORDINAL 或 STRING)。 | 加在枚举字段上。 | 将枚举存储为数字或字符串。 | java @Enumerated(EnumType.STRING) private Role role; |
@Lob |
标记大字段(CLOB、BLOB)。 | 加在字段上。 | 存储大文本或二进制数据。 | java @Lob private String description; // CLOB @Lob private byte[] image; // BLOB |
@OneToOne |
一对一关联关系。 | 加在关联字段上。 | 实体间一对一关系。 | java @OneToOne @JoinColumn(name = "address_id") private Address address; |
@OneToMany |
一对多关联关系。 | 加在集合字段上。 | 实体间一对多关系。 | java @OneToMany(mappedBy = "user") private List<Order> orders; |
@ManyToOne |
多对一关联关系。 | 加在关联字段上。 | 实体间多对一关系。 | java @ManyToOne @JoinColumn(name = "user_id") private User user; |
@ManyToMany |
多对多关联关系。 | 加在集合字段上。 | 实体间多对多关系。 | java @ManyToMany @JoinTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id")) private List<Role> roles; |
@JoinColumn |
指定外键列。 | 用在关联注解中。 | 定义外键列名。 | 见上例。 |
@JoinTable |
指定中间表。 | 用在 @ManyToMany 中。 |
定义中间表及外键列。 | 见上例。 |
@MappedSuperclass |
标记父类,子类可继承其映射信息。 | 加在父类上。 | 抽取公共字段(如 id、创建时间)。 | java @MappedSuperclass public class BaseEntity { @Id @GeneratedValue private Long id; private LocalDateTime createTime; // getter/setter } |
@EntityListeners |
指定实体监听器。 | 加在实体类上。 | 监听实体生命周期事件。 | java @Entity @EntityListeners(AuditingEntityListener.class) public class User { @CreatedDate private LocalDateTime createdAt; } |
@PrePersist / @PreUpdate 等 |
实体生命周期回调方法。 | 加在方法上。 | 在实体操作前/后执行自定义逻辑。 | java @PrePersist public void prePersist() { this.createdAt = LocalDateTime.now(); } |
@Query |
在 Repository 方法上定义自定义 JPQL 或 SQL 查询。 | 加在 Repository 方法上。 | 复杂查询,非方法命名能表达。 | java @Repository public interface UserRepository extends JpaRepository<User, Long> { @Query("SELECT u FROM User u WHERE u.email = :email") User findByEmail(@Param("email") String email); } |
@Modifying |
标识方法执行更新操作(配合 @Query)。 |
加在 Repository 方法上。 | 执行 UPDATE/DELETE 操作。 | java @Modifying @Query("UPDATE User u SET u.status = :status WHERE u.lastLoginDate < :date") int deactivateInactiveUsers(@Param("date") LocalDate date, @Param("status") String status); |
@Param |
为查询参数命名,便于在 @Query 中引用。 |
方法参数上。 | 显式指定参数名。 | 见上例。 |
@Transactional |
声明事务边界(可加在类或方法上)。 | 类或方法上。 | 控制事务。 | 见事务管理部分。 |
5. 事务管理注解
| 注解 | 作用 | 用法 | 场景 | 代码举例 |
|---|---|---|---|---|
@Transactional |
声明式事务管理,可配置传播行为、隔离级别、超时、只读等属性。 | 类或方法上。 | 需要事务支持的业务方法。 | java @Service public class UserService { @Transactional public void createUser(User user) { userRepository.save(user); // 可能还有其他数据库操作 } } |
6. 缓存注解
| 注解 | 作用 | 用法 | 场景 | 代码举例 |
|---|---|---|---|---|
@EnableCaching |
开启缓存功能。 | 加在配置类或启动类上。 | 启用 Spring 缓存抽象。 | java @SpringBootApplication @EnableCaching public class Application { ... } |
@Cacheable |
方法执行前先查询缓存,若缓存存在则直接返回,否则执行方法并缓存结果。 | 方法上。 | 缓存方法结果,适用于读多写少。 | java @Cacheable(value = "users", key = "#id") public User findById(Long id) { return userRepository.findById(id).orElse(null); } |
@CachePut |
总是执行方法,并将结果更新到缓存。 | 方法上。 | 更新缓存中的数据。 | java @CachePut(value = "users", key = "#user.id") public User update(User user) { return userRepository.save(user); } |
@CacheEvict |
清除缓存。 | 方法上。 | 删除缓存项。 | java @CacheEvict(value = "users", key = "#id") public void delete(Long id) { userRepository.deleteById(id); } |
@Caching |
组合多个缓存注解。 | 方法上。 | 同时应用多个缓存操作。 | java @Caching( put = { @CachePut(value = "users", key = "#user.id") }, evict = { @CacheEvict(value = "users", key = "#user.email") } ) public User save(User user) { ... } |
@CacheConfig |
类级别共享缓存配置(如缓存名称)。 | 类上。 | 统一指定缓存名称等。 | java @Service @CacheConfig(cacheNames = "users") public class UserService { @Cacheable(key = "#id") public User findById(Long id) { ... } } |
7. 异步与定时任务注解
| 注解 | 作用 | 用法 | 场景 | 代码举例 |
|---|---|---|---|---|
@EnableAsync |
开启异步方法支持。 | 加在配置类或启动类上。 | 启用 @Async 注解。 |
java @SpringBootApplication @EnableAsync public class Application { ... } |
@Async |
标注方法为异步执行,调用后立即返回。 | 方法上。 | 执行耗时任务(如发送邮件、日志记录)。 | java @Service public class EmailService { @Async public void sendEmail(String to, String subject, String body) { // 模拟耗时操作 Thread.sleep(5000); System.out.println("Email sent to " + to); } } |
@EnableScheduling |
开启定时任务支持。 | 加在配置类或启动类上。 | 启用 @Scheduled 注解。 |
java @SpringBootApplication @EnableScheduling public class Application { ... } |
@Scheduled |
标注方法为定时任务,可配置 cron、fixedDelay、fixedRate 等。 | 方法上。 | 定时执行任务(如数据清理、报表生成)。 | java @Component public class ScheduledTasks { @Scheduled(cron = "0 0 2 * * ?") // 每天凌晨2点执行 public void performCleanup() { System.out.println("Cleaning up..."); } } |
8. 异常处理与控制器增强
| 注解 | 作用 | 用法 | 场景 | 代码举例 |
|---|---|---|---|---|
@ControllerAdvice |
全局控制器增强,可定义全局异常处理、数据绑定、模型属性等。 | 加在类上。 | 统一处理控制器层的异常、数据绑定等。 | java @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) @ResponseBody public ResponseEntity<String> handleException(Exception e) { return ResponseEntity.status(500).body(e.getMessage()); } } |
@RestControllerAdvice |
组合注解 = @ControllerAdvice + @ResponseBody,用于 REST API 全局异常处理。 |
加在类上。 | RESTful 风格的全局异常处理。 | java @RestControllerAdvice public class RestExceptionHandler { @ExceptionHandler(ResourceNotFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) public Map<String, String> handleNotFound(ResourceNotFoundException e) { return Map.of("error", e.getMessage()); } } |
@ExceptionHandler |
标注在方法上,处理特定异常。 | 方法上,通常位于 @ControllerAdvice 类中或控制器内部。 |
处理控制器抛出的异常。 | 见上例。 |
@InitBinder |
自定义数据绑定器,如日期格式化。 | 方法上,通常位于控制器或 @ControllerAdvice 中。 |
处理请求参数到对象的绑定。 | java @InitBinder public void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false)); } |
@ModelAttribute |
在 @ControllerAdvice 中定义全局模型属性。 |
方法上。 | 为所有控制器添加公共模型数据。 | java @ControllerAdvice public class GlobalModelAttributes { @ModelAttribute("appName") public String appName() { return "MyApp"; } } |
9. 跨域支持注解
| 注解 | 作用 | 用法 | 场景 | 代码举例 |
|---|---|---|---|---|
@CrossOrigin |
允许跨域请求,可加在类或方法上,配置允许的来源、方法等。 | 类或方法上。 | 解决前后端分离的跨域问题。 | java @RestController @RequestMapping("/api") @CrossOrigin(origins = "http://localhost:3000") public class ApiController { @GetMapping("/data") public String getData() { return "data"; } } |
10. 条件化配置注解(自动配置相关)
这些注解通常用于自动配置类或自定义条件配置。
| 注解 | 作用 | 用法 | 场景 | 代码举例 |
|---|---|---|---|---|
@Conditional |
根据条件决定是否创建 Bean。 | 加在类或 @Bean 方法上,需指定 Condition 实现类。 |
高级条件配置。 | 一般用 Spring Boot 提供的专用条件注解。 |
@ConditionalOnClass |
当类路径下存在指定类时生效。 | 加在配置类或 @Bean 方法上。 |
根据依赖库决定配置。 | java @Configuration @ConditionalOnClass(DataSource.class) public class DataSourceAutoConfiguration { ... } |
@ConditionalOnMissingClass |
当类路径下不存在指定类时生效。 | 同上。 | 类不存在时启用备选配置。 | java @Bean @ConditionalOnMissingClass("com.mysql.jdbc.Driver") public DataSource h2DataSource() { ... } |
@ConditionalOnBean |
当容器中存在指定 Bean 时生效。 | 同上。 | 依赖某个 Bean 存在时才配置。 | java @Bean @ConditionalOnBean(JdbcTemplate.class) public MyRepository myRepository(JdbcTemplate jdbcTemplate) { ... } |
@ConditionalOnMissingBean |
当容器中不存在指定 Bean 时生效。 | 同上。 | 提供默认 Bean,若用户未定义则创建。 | java @Bean @ConditionalOnMissingBean public MyService defaultMyService() { return new DefaultMyService(); } |
@ConditionalOnProperty |
当配置文件中存在指定属性且值匹配时生效。 | 同上。 | 根据配置项决定是否启用。 | java @Bean @ConditionalOnProperty(name = "app.feature.enabled", havingValue = "true") public FeatureService featureService() { ... } |
@ConditionalOnResource |
当类路径下存在指定资源文件时生效。 | 同上。 | 根据资源文件存在决定配置。 | java @ConditionalOnResource(resources = "META-INF/spring/beans.xml") |
@ConditionalOnWebApplication |
当项目是 Web 应用时生效。 | 同上。 | Web 环境下的特定配置。 | java @Configuration @ConditionalOnWebApplication public class WebConfig { ... } |
@ConditionalOnNotWebApplication |
当项目不是 Web 应用时生效。 | 同上。 | 非 Web 环境下的配置。 | 同上,反向条件。 |
@ConditionalOnExpression |
当 SpEL 表达式计算结果为 true 时生效。 | 同上。 | 复杂条件判断。 | java @ConditionalOnExpression("${app.feature.enabled:false} and T(java.time.LocalDate).now().dayOfWeek.value==1") |
11. 测试注解
| 注解 | 作用 | 用法 | 场景 | 代码举例 |
|---|---|---|---|---|
@SpringBootTest |
加载完整的 Spring 应用上下文进行集成测试。 | 加在测试类上。 | 测试整个 Spring Boot 应用。 | java @SpringBootTest class ApplicationTests { @Test void contextLoads() { } } |
@WebMvcTest |
仅测试 Web 层,只加载控制器相关的 Bean。 | 加在测试类上。 | 测试 Controller 层,不加载 Service、Repository 等。 | java @WebMvcTest(UserController.class) class UserControllerTest { @Autowired private MockMvc mockMvc; @MockBean private UserService userService; // ... } |
@DataJpaTest |
仅测试 JPA 层,自动配置内存数据库等。 | 加在测试类上。 | 测试 Repository 层。 | java @DataJpaTest class UserRepositoryTest { @Autowired private TestEntityManager entityManager; @Autowired private UserRepository userRepository; // ... } |
@JsonTest |
测试 JSON 序列化/反序列化。 | 加在测试类上。 | 测试 JSON 转换。 | java @JsonTest class UserJsonTest { @Autowired private JacksonTester<User> json; // ... } |
@RestClientTest |
测试 REST 客户端。 | 加在测试类上。 | 测试 RestTemplate 或 WebClient。 | java @RestClientTest(UserService.class) class UserServiceTest { @Autowired private MockRestServiceServer server; @Autowired private UserService userService; } |
@MockBean |
在测试上下文中创建 Mockito 的 Mock 对象替换原有 Bean。 | 字段或类上。 | 模拟依赖,隔离测试。 | 见 @WebMvcTest 示例。 |
@SpyBean |
创建 Spy 对象。 | 同上。 | 部分模拟真实 Bean。 | java @SpyBean private UserService userService; |
@Test |
JUnit 测试方法。 | 方法上。 | 标记测试方法。 | 见上例。 |
@BeforeEach / @AfterEach |
JUnit5 中的生命周期方法,在每个测试方法前/后执行。 | 方法上。 | 准备/清理测试数据。 | java @BeforeEach void setUp() { // 初始化 } |
@Transactional |
在测试中用于事务回滚,保证测试数据隔离。 | 方法或类上。 | 测试后自动回滚数据库更改。 | java @Test @Transactional void testCreateUser() { // 操作数据库,测试后回滚 } |
@Sql |
执行 SQL 脚本。 | 方法或类上。 | 测试前加载数据。 | java @Test @Sql("/test-data.sql") void testWithData() { ... } |
@AutoConfigureMockMvc |
自动配置 MockMvc 用于测试 Controller。 | 加在测试类上(常与 @SpringBootTest 配合)。 |
测试控制器。 | java @SpringBootTest @AutoConfigureMockMvc class MyControllerTest { @Autowired private MockMvc mockMvc; } |
12. Lombok 常用注解(简化代码)
| 注解 | 作用 | 用法 | 场景 | 代码举例 |
|---|---|---|---|---|
@Data |
生成 getter/setter、equals()、hashCode()、toString() 等。 |
加在类上。 | 简化 POJO 类。 | java @Data public class User { private Long id; private String name; } |
@Getter / @Setter |
生成 getter 或 setter。 | 加在类或字段上。 | 灵活控制生成。 | java @Getter @Setter public class User { private Long id; } |
@NoArgsConstructor |
生成无参构造器。 | 加在类上。 | JPA 实体等需要无参构造。 | java @Entity @NoArgsConstructor public class User { ... } |
@AllArgsConstructor |
生成全参构造器。 | 加在类上。 | 方便创建对象。 | java @AllArgsConstructor public class User { private Long id; private String name; } |
@RequiredArgsConstructor |
生成包含 final 或 @NonNull 字段的构造器。 |
加在类上。 | 依赖注入时配合 @NonNull 或 final 字段。 |
java @Service @RequiredArgsConstructor public class UserService { private final UserRepository userRepository; } |
@Builder |
实现建造者模式。 | 加在类上。 | 构建复杂对象。 | java @Builder public class User { private Long id; private String name; } // 使用 User user = User.builder().id(1L).name("John").build(); |
@ToString |
生成 toString() 方法。 |
加在类上。 | 自定义 toString。 | java @ToString(exclude = "password") public class User { ... } |
@EqualsAndHashCode |
生成 equals() 和 hashCode() 方法。 |
加在类上。 | 需要比较对象时。 | java @EqualsAndHashCode(of = "id") public class User { ... } |
@Slf4j |
自动生成 log 字段(基于 SLF4J)。 | 加在类上。 | 日志记录。 | java @Service @Slf4j public class UserService { public void doSomething() { log.info("Doing something"); } } |
@Log4j / @Log4j2 |
生成对应的日志对象。 | 类上。 | 使用 Log4j 日志框架。 | 类似 @Slf4j。 |
@NonNull |
用于字段或参数,自动生成空值检查。 | 字段或参数上。 | 防止 NullPointerException。 | java public void setName(@NonNull String name) { this.name = name; } |
@Value |
生成不可变类(所有字段为 private final,不生成 setter)。 | 类上。 | 创建 DTO 或值对象。 | java @Value public class ImmutableUser { Long id; String name; } |
13. Spring Security 常用注解
| 注解 | 作用 | 用法 | 场景 | 代码举例 |
|---|---|---|---|---|
@EnableWebSecurity |
启用 Spring Security Web 安全功能。 | 加在配置类上。 | 自定义安全配置。 | java @Configuration @EnableWebSecurity public class SecurityConfig { ... } |
@EnableGlobalMethodSecurity |
开启方法级安全控制,可配置 prePostEnabled、securedEnabled 等。 | 加在配置类上。 | 启用方法级别的权限注解。 | java @Configuration @EnableGlobalMethodSecurity(prePostEnabled = true) public class MethodSecurityConfig { ... } |
@Secured |
指定方法需要的角色列表。 | 方法上。 | 基于角色的方法访问控制。 | java @Secured("ROLE_ADMIN") public void adminOnly() { ... } |
@PreAuthorize |
方法执行前进行权限表达式校验。 | 方法上。 | 灵活的权限控制(支持 SpEL)。 | java @PreAuthorize("hasRole('ADMIN') or #id == authentication.principal.id") public void updateUser(Long id) { ... } |
@PostAuthorize |
方法执行后进行权限表达式校验。 | 方法上。 | 根据返回结果进行权限检查。 | java @PostAuthorize("returnObject.owner == authentication.name") public User getUser(Long id) { ... } |
@PreFilter / @PostFilter |
过滤集合类型的参数或返回值。 | 方法上。 | 对集合进行权限过滤。 | java @PreFilter("filterObject.owner == authentication.name") public void saveAll(List<User> users) { ... } |
@AuthenticationPrincipal |
获取当前认证用户的 Principal 对象。 | 方法参数上。 | 在控制器中获取当前用户信息。 | java @GetMapping("/me") public User getCurrentUser(@AuthenticationPrincipal UserDetails userDetails) { return userService.findByUsername(userDetails.getUsername()); } |
@CurrentSecurityContext |
获取当前 SecurityContext。 | 方法参数上。 | 获取 SecurityContext 中的信息。 | java @GetMapping("/ctx") public String getContext(@CurrentSecurityContext SecurityContext context) { return context.getAuthentication().getName(); } |
14. 其他常用注解
| 注解 | 作用 | 用法 | 场景 | 代码举例 |
|---|---|---|---|---|
@Bean |
标注在方法上,将方法返回值注册为一个 Spring Bean。 | 方法上,通常位于 @Configuration 类中。 |
注册第三方库的实例或自定义 Bean。 | java @Configuration public class AppConfig { @Bean public RestTemplate restTemplate() { return new RestTemplate(); } } |
@Profile |
指定 Bean 在某个或某些 profile 环境下生效。 | 类或方法上。 | 不同环境加载不同 Bean。 | java @Component @Profile("dev") public class DevDataSource { ... } |
@EventListener |
监听应用程序事件。 | 方法上,参数为事件类型。 | 处理自定义事件或 Spring 内置事件。 | java @Component public class MyListener { @EventListener public void handleContextRefresh(ContextRefreshedEvent event) { System.out.println("Context refreshed"); } } |
@EnableConfigurationProperties |
启用对 @ConfigurationProperties 的支持。 |
加在配置类上,指定要注册的 properties 类。 | 使 @ConfigurationProperties 类生效。 |
java @Configuration @EnableConfigurationProperties(AppProperties.class) public class AppConfig { } |
@EnableTransactionManagement |
启用注解式事务管理(Spring Boot 自动配置,通常无需手动添加)。 | 配置类上。 | 如果默认不生效,可手动开启。 | 一般不常用。 |
@EnableJpaRepositories |
启用 JPA Repository 并指定扫描包。 | 配置类上。 | 自定义 JPA Repository 位置。 | java @Configuration @EnableJpaRepositories(basePackages = "com.example.repository") public class JpaConfig { } |
@EntityScan |
指定实体类扫描包。 | 配置类上。 | 如果实体不在主包下,需指定扫描路径。 | java @Configuration @EntityScan("com.example.entity") public class JpaConfig { } |
@ServletComponentScan |
扫描 Servlet 组件(如 Filter、Listener、Servlet)。 | 启动类或配置类上。 | 使用原生的 Servlet 组件。 | java @SpringBootApplication @ServletComponentScan public class Application { } |
以上涵盖了 Spring Boot Web 后端开发中绝大多数常用注解,并提供了作用、用法、场景及代码示例。