Java 面试知识整理(四):Spring Boot 注解大全

控制器层(Controller Layer)

注解用途代码示例
@RestController定义 REST API 控制器,返回 JSON@RestController public class UserController {}
@RequestMapping定义请求路径@RequestMapping("/api/users")
@GetMappingGET 请求@GetMapping("/{id}")
@PostMappingPOST 请求@PostMapping
@PutMappingPUT 请求@PutMapping
@DeleteMappingDELETE 请求@DeleteMapping("/{id}")
@RequestParam接收 URL 参数@RequestParam Long id
@PathVariable接收路径参数@PathVariable Long id
@RequestBody接收 JSON 请求体@RequestBody User user

业务层(Service Layer)

注解用途
@Service标记为 Service 层 Bean
@Transactional声明式事务管理

持久层(DAO Layer)

注解用途
@Repository标记为 DAO 层 Bean
@MapperMyBatis 的 Mapper 接口

通用注解

注解用途
@Component通用 Bean,不属于 Controller/Service/Repository 的用这个
@Autowired依赖注入
@Value读取配置文件的值
@Configuration标记为配置类
@Bean在配置类中声明 Bean

AOP 注解

注解用途
@Aspect定义切面类
@Before前置通知
@After后置通知
@Around环绕通知
@Pointcut定义切点

Bean 生命周期注解

注解用途
@PostConstructBean 初始化完成后执行
@PreDestroyBean 销毁前执行

其他常用注解

注解用途
@SpringBootApplicationSpring Boot 启动类
@ConfigurationProperties批量读取配置
@Slf4jLombok 日志注解
@DataLombok,自动生成 getter/setter
@Valid / @Validated参数校验