Spring Boot 核心注解

226 阅读3分钟

Spring Boot 核心注解

一、启动类与配置类

1. @SpringBootApplication

作用:应用入口,整合 @Configuration@EnableAutoConfiguration@ComponentScan。 • 示例

@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

2. @Configuration

作用:标记配置类,用于定义 Bean。 • 常用搭配@Bean示例

@Configuration
public class AppConfig {
    @Bean
    public MyService myService() {
        return new MyService();
    }
}

二、控制器与 REST API

3. @RestController

作用@Controller + @ResponseBody,返回 JSON/XML 数据。 • 示例

@RestController
@RequestMapping("/api/users")
public class UserController { ... }

4. @RequestMapping

作用:映射请求路径,支持类/方法级别。 • 属性pathmethod(GET/POST等)。 • 示例

@RequestMapping("/users")
public class UserController { ... }

@PostMapping("/create")
public User createUser(@Valid @RequestBody User user) { ... }

5. HTTP 方法注解

@GetMapping:GET 请求
@PostMapping:POST 请求
@PutMapping:PUT 请求
@DeleteMapping:DELETE 请求


三、依赖注入

6. @Autowired

作用:自动注入 Spring 容器中的 Bean。 • 适用场景:字段、构造方法、方法参数。 • 示例

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;
}

7. 组件注解

注解作用使用场景
@Component通用组件任意层
@Service业务逻辑层Service 类
@Repository数据访问层DAO 接口/实现类
@ControllerMVC 控制器控制器类

四、数据访问与 JPA

8. @Entity

作用:标记 JPA 实体类,对应数据库表。 • 示例

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
}

9. @Repository

作用:继承 JpaRepository,提供 CRUD 和分页功能。 • 示例

public interface UserRepository extends JpaRepository<User, Long> { ... }

五、事务管理

10. @Transactional

作用:声明式事务管理,自动控制事务提交/回滚。 • 示例

@Service
@Transactional
public class UserService {
    public void createUser(User user) {
        userRepository.save(user);
        // 异常触发回滚
    }
}

六、验证与异常处理

11. @Validated

作用:启用方法参数和返回值验证。 • 示例

@Validated
@Service
public class UserService {
    public void createUser(@Valid @RequestBody User user) { ... }
}

12. @Valid / @NotBlank

作用:字段验证,如非空、格式校验。 • 示例

public class User {
    @NotBlank(message = "用户名不能为空")
    private String name;
}

七、其他常用注解

13. @PathVariable

作用:绑定 URL 路径参数。 • 示例

@GetMapping("/{id}")
public User getUserById(@PathVariable Long id) { ... }

14. @RequestParam

作用:绑定 HTTP 请求参数。 • 示例

@GetMapping("/search?name={name}")
public List<User> searchUser(@RequestParam String name) { ... }

八、核心注解速查表

注解作用典型场景
@SpringBootApplication应用启动类主类
@RestControllerRESTful API 控制器控制器类
@Autowired依赖注入字段/构造方法
@EntityJPA 实体类映射数据模型类
@Repository数据访问层组件DAO 接口
@Transactional声明式事务管理服务类方法
@GetMapping映射 GET 请求控制器方法
@PathVariable绑定 URL 路径参数控制器方法参数
@Validated启用方法参数验证服务类

九、学习建议

  1. 动手实践:创建项目,逐步添加注解观察效果。
  2. 文档参考Spring Boot 官方文档
  3. 避坑提示: • @SpringBootApplication 的扫描路径默认为主类包及其子包。 • 使用 @Valid 时需在启动类添加 @Validated
  4. 进阶学习:结合 Spring Security、MyBatis 等扩展注解。

整理说明
以上笔记覆盖了 Spring Boot 开发的核心注解,建议通过小项目(如 CRUD API、集成数据库)逐步掌握每个注解的实际用法。遇到问题优先查阅官方文档和社区资源(如 Stack Overflow)。