Spring Boot 常用注解大全:从入门到进阶
Spring Boot 常用注解大全:从入门到进阶
Spring Boot 的强大在于它通过 注解驱动的方式 简化了配置与开发。本文将分 核心 → Web → 数据 → 进阶 四大部分介绍,并且 每个注解都配上示例,帮助你快速上手。
一、核心注解与配置 (Core & Configuration)
1. @SpringBootApplication
应用的入口注解,组合了配置、自动装配和组件扫描。
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
2. @Configuration
标记配置类。
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyServiceImpl();
}
}
3. @Bean
方法返回的对象会注册为 Bean。
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
4. @Value
注入配置文件属性。
@Value("${server.port}")
private int port;
@Value("Hello Spring Boot")
private String msg;
5. @ConfigurationProperties
批量绑定配置。
application.properties
app.mail.host=smtp.example.com
app.mail.port=587
Java 类
@Component
@ConfigurationProperties(prefix = "app.mail")
public class MailProperties {
private String host;
private int port;
// getters & setters
}
6. @Autowired
自动注入依赖。
@Service
public class UserService {
private final UserRepository repo;
// 推荐构造器注入
public UserService(UserRepository repo) {
this.repo = repo;
}
}
7. @Qualifier
解决多实现冲突。
@Autowired
@Qualifier("fastRepo")
private UserRepository repo;
8. @Primary
多个 Bean 时默认优先注入。
@Repository
@Primary
public class DefaultUserRepository implements UserRepository {}
9. @Lazy
延迟加载 Bean。
@Autowired
@Lazy
private HeavyService heavyService;
10. @Component / @Service / @Repository / @Controller
@Component
public class CommonUtil {}
@Service
public class OrderService {}
@Repository
public class OrderRepository {}
@Controller
public class HomeController {}
二、Web MVC 相关注解 (Web & REST)
1. @RestController
组合注解(@Controller + @ResponseBody)。
@RestController
@RequestMapping("/api/users")
public class UserController {
@GetMapping
public List<User> findAll() {
return List.of(new User(1L, "Tom"), new User(2L, "Jerry"));
}
}
2. @RequestMapping & 派生注解
@GetMapping("/hello")
public String hello() {
return "Hello World";
}
@PostMapping("/users")
public User create(@RequestBody User u) {
return u;
}
3. @RequestParam
获取查询参数。
@GetMapping("/search")
public String search(@RequestParam String name,
@RequestParam(defaultValue = "20") int age) {
return name + " - " + age;
}
4. @PathVariable
获取路径参数。
@GetMapping("/users/{id}")
public String getUser(@PathVariable Long id) {
return "UserId = " + id;
}
5. @RequestBody
绑定请求体 JSON。
@PostMapping("/users")
public User add(@RequestBody User user) {
return user;
}
6. @CrossOrigin
解决跨域问题。
@CrossOrigin(origins = "http://localhost:3000")
@GetMapping("/data")
public String getData() {
return "CORS OK";
}
7. @ExceptionHandler + @ControllerAdvice
全局异常处理。
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handle(Exception e) {
return ResponseEntity.status(500).body("Error: " + e.getMessage());
}
}
8. @Validated / @Valid
参数校验。
@PostMapping("/users")
public String createUser(@Valid @RequestBody UserDto dto) {
return "OK";
}
三、数据访问注解 (Data Access)
1. @Entity + @Table
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue
private Long id;
@Column(nullable = false)
private String name;
}
2. @Transactional
声明事务。
@Service
public class AccountService {
@Transactional
public void transfer(Long from, Long to, BigDecimal amt) { ... }
}
3. @Query + @Modifying
public interface UserRepository extends JpaRepository<User, Long> {
@Query("select u from User u where u.name=?1")
List<User> findByName(String name);
@Modifying
@Query("delete from User u where u.age<?1")
void deleteByAgeLessThan(int age);
}
四、进阶与扩展注解 (Advanced)
1. 定时任务
@EnableScheduling
@SpringBootApplication
public class App {}
@Component
public class TaskJob {
@Scheduled(fixedRate = 5000)
public void run() {
System.out.println("Run every 5s");
}
}
2. 异步任务
@EnableAsync
@SpringBootApplication
public class App {}
@Service
public class AsyncService {
@Async
public void runTask() {
System.out.println("Async running");
}
}
3. 缓存
@EnableCaching
@SpringBootApplication
public class App {}
@Service
public class ProductService {
@Cacheable("products")
public String getProduct(Long id) {
return "Product-" + id;
}
}
4. Profile 环境管理
@Service
@Profile("dev")
public class DevService {}
@Service
@Profile("prod")
public class ProdService {}
5. 条件化加载
@Configuration
@ConditionalOnClass(name = "com.mysql.cj.jdbc.Driver")
public class MySqlConfig {
// 仅在 classpath 有 MySQL 驱动时生效
}
五、常用注解总结表(带示例)
注解 | 类别 | 示例 |
@SpringBootApplication | 核心 | SpringApplication.run(App.class) |
@Configuration / @Bean | 核心 | @Bean public PasswordEncoder encoder() |
@Autowired / @Qualifier / @Primary | 核心 | 构造器注入依赖 |
@Value / @ConfigurationProperties | 核心 | @Value("${server.port}") |
@Component / @Service / @Repository / @Controller | 核心 | 标记不同层次组件 |
@RestController / @GetMapping | Web | @GetMapping("/hello") |
@RequestParam / @PathVariable / @RequestBody | Web | 获取参数、绑定请求体 |
@Validated / @Valid | Web | 校验 DTO |
@CrossOrigin | Web | 解决跨域 |
@ExceptionHandler / @ControllerAdvice | Web | 全局异常处理 |
@Entity / @Id / @Table | 数据 | 定义 JPA 实体 |
@Transactional | 数据 | @Transactional public void transfer() |
@EnableScheduling / @Scheduled | 进阶 | 定时任务 |
@EnableAsync / @Async | 进阶 | 异步方法 |
@EnableCaching / @Cacheable | 进阶 | 缓存数据 |
@Profile | 进阶 | 环境切换 |
@ConditionalOnClass 等 | 进阶 | 条件化配置 |
总结
- 入门必备:@SpringBootApplication、@RestController、@Autowired、@Value。
- 进阶常用:@ConfigurationProperties、@Transactional、@ControllerAdvice、@Scheduled、@Async。
- 专家进阶:@Cacheable、@Profile、@ConditionalOnClass。
掌握这些注解,你就能覆盖 90% 的 Spring Boot 开发场景。
相关文章
- Spring Boot中对接Twilio以实现发送验证码和验证短信码
- Spring Boot 3.5:这次更新让你连配置都不用写了,惊不惊喜?
- Spring Boot+Pinot实战:毫秒级实时竞价系统构建
- SpringBoot敏感配置项加密与解密实战
- SpringBoot 注解最全详解,建议收藏!
- Spring Boot 常用注解大全:从入门到进阶
- SpringBoot启动之谜:@SpringBootApplication如何让配置化繁为简
- Springboot集成Kafka原理_spring集成kafka的原理
- Spring Boot中@Data注解的深度解析与实战应用
- 大佬用1000字就把SpringBoot的配置文件讲的明明白白!