SpringBoot多场景中23种常用注解详解
一、核心注解
- @SpringBootApplication
作用:主配置类注解,组合了@Configuration、@EnableAutoConfiguration和@ComponentScan
@SpringBootApplicationpublic class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); }}
- @RestController
作用:组合了@Controller和@ResponseBody,表示该类是控制器且返回值直接写入HTTP响应体
@RestController
@RequestMapping("/api")
public class MyController {@GetMapping("/hello") public String sayHello() { return "Hello, Spring Boot!"; }}
二、依赖注入相关注解
3. @Autowired
作用:自动装配依赖对象
@Service
public class UserService {
public String getUser() { return "User Info"; }}
@RestController
public class UserController {@Autowired private UserService userService;@GetMapping("/user") public String getUser() { return userService.getUser(); }}
- @Component, @Service, @Repository
作用:将类标记为Spring组件,分别用于通用组件、服务层和数据访问层
@Repository
public class UserRepository { // 数据访问逻辑}
@Service
public class UserService {@Autowired private UserRepository userRepository;// 业务逻辑}
三、Web MVC相关注解
5. @RequestMapping
作用:映射Web请求路径
@RestController
@RequestMapping("/api/users")
public class UserController {@RequestMapping(value = "/{id}", method = RequestMethod.GET) public User getUser(@PathVariable Long id) { // 获取用户逻辑 }}
- @GetMapping, @PostMapping, @PutMapping, @DeleteMapping
作用:特定HTTP方法的简化注解
@RestController
public class UserController {@GetMapping("/users") public List<User> getAllUsers() { // 获取所有用户 }@PostMapping("/users") public User createUser(@RequestBody User user) { / / 创建用户 }@PutMapping("/users/{id}") public User updateUser(@PathVariable Long id, @RequestBody User user) { // 更新用户 }@DeleteMapping("/users/{id}") public void deleteUser(@PathVariable Long id) { // 删除用户 }}
- @PathVariable
作用:获取URL路径中的变量
@GetMapping("/users/{id}")
public User getUser(@PathVariable("id") Long userId) { // 根据userId获取用户
}
- @RequestParam
作用:获取请求参数
@GetMapping("/users")public List<User> getUsersByPage( @RequestParam(value = "page", defaultValue = "1") int page, @RequestParam(value = "size", defaultValue = "10") int size) { // 分页查询逻辑}
- @RequestBody
作用:将HTTP请求体绑定到方法参数
@PostMapping(“/users”)
public User createUser(@RequestBody User user) {
// 创建用户逻辑
} - @ResponseBody
作用:将方法返回值直接写入HTTP响应体
@Controller
public class UserController {@GetMapping("/user/{id}") @ResponseBody public User getUser(@PathVariable Long id) { // 获取用户逻辑 }}
四、配置相关注解
10. @Configuration
作用:声明一个类为配置类
@Configurationpublic class AppConfig {@Bean public MyService myService() { return new MyServiceImpl(); }}
- @Bean
作用:声明一个方法的返回值为Bean
@Configuration
public class AppConfig {@Bean public DataSource dataSource() { // 配置并返回DataSource }}
- @Value
作用:注入属性值
@Service
public class MyService {@Value("${app.name}") private String appName;@Value("${app.version:1.0.0}") // 默认值 private String appVersion;
}
- @ConfigurationProperties
作用:批量注入配置属性
@Configuration
@ConfigurationProperties(prefix = "app")
public class AppProperties { private String name; private String version; private List<String> servers = new ArrayList<>();// getters and setters
}//application.propertiesapp.name=MyAppapp.version=2.0.0app.servers=server1,server2,server3
五、AOP相关注解1
15. @Aspect
作用:声明一个切面类
@Aspect@Componentpublic class LoggingAspect {@Before("execution(* com.example.service.*.*(..))") public void logBefore(JoinPoint joinPoint) { System.out.println("Before method: " + joinPoint.getSignature().getName()); }@AfterReturning(pointcut = "execution(* com.example.service.*.*(..))", returning = "result") public void logAfterReturning(JoinPoint joinPoint, Object result) { System.out.println("Method " + joinPoint.getSignature().getName() + " returned: " + result); }}
六、事务管理
16. @Transactional
作用:声明事务
@Service
public class UserService {@Autowired private UserRepository userRepository;@Transactional public User createUser(User user) { // 事务操作 return userRepository.save(user); }@Transactional(readOnly = true) public User getUser(Long id) { return userRepository.findById(id).orElse(null); }}
七、测试相关注解
17. @SpringBootTest
作用:Spring Boot集成测试
@SpringBootTest
class UserServiceTest {@Autowired private UserService userService;@Test void testCreateUser() { User user = new User("test", "test@example.com"); User savedUser = userService.createUser(user); assertNotNull(savedUser.getId()); }}
- @MockBean
作用:在测试中模拟Bean
@SpringBootTestclass UserServiceTest {@Autowired private UserService userService;@MockBean private UserRepository userRepository;@Test void testGetUser() { User mockUser = new User(1L, "mock", "mock@example.com"); when(userRepository.findById(1L)).thenReturn(Optional.of(mockUser));User user = userService.getUser(1L); assertEquals("mock", user.getName()); }}
八、异常处理
19. @ControllerAdvice
作用:全局异常处理
@ControllerAdvice
public class GlobalExceptionHandler {@ExceptionHandler(ResourceNotFoundException.class) public ResponseEntity<ErrorResponse> handleResourceNotFound(ResourceNotFoundException ex) { ErrorResponse error = new ErrorResponse("NOT_FOUND", ex.getMessage()); return new ResponseEntity<>(error, HttpStatus.NOT_FOUND); }@ExceptionHandler(Exception.class) public ResponseEntity<ErrorResponse> handleAllExceptions(Exception ex) { ErrorResponse error = new ErrorResponse("INTERNAL_ERROR", "An unexpected error occurred"); return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR); }}
九、定时任务
20. @Scheduled
作用:定时任务
@Componentpublic class ScheduledTasks {private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);@Scheduled(fixedRate = 5000) // 每5秒执行一次 public void reportCurrentTime() { log.info("Current time is {}", new Date()); }@Scheduled(cron = "0 0 12 * * ?") // 每天中午12点执行 public void dailyTask() { log.info("Executing daily task"); }
}
10、缓存相关
21. @Cacheable, @CacheEvict, @CachePut
作用:声明式缓存
@Service
public class ProductService {@Cacheable(value = "products", key = "#id") public Product getProductById(Long id) { // 模拟耗时操作 try { Thread.sleep(3000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return new Product(id, "Product " + id, 100.0); }@CacheEvict(value = "products", key = "#id") public void refreshProduct(Long id) { // 清除缓存 }@CachePut(value = "products", key = "#product.id") public Product updateProduct(Product product) { // 更新产品并更新缓存 return product; }}
十一、验证相关
22. @Valid, @Validated
作用:参数验证
@RestController
public class UserController {@PostMapping("/users") public ResponseEntity<User> createUser(@Valid @RequestBody User user) { // 处理验证通过的用户 return ResponseEntity.ok(user); }}public class User {@NotBlank(message = "Name is mandatory") private String name;@Email(message = "Email should be valid") private String email;@Min(value = 18, message = "Age should not be less than 18") @Max(value = 150, message = "Age should not be greater than 150") private int age;// getters and setters}
十二、跨域处理
23. @CrossOrigin
作用:处理跨域请求
@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "http://example.com", maxAge = 3600)
public class MyController {@GetMapping("/items") @CrossOrigin // 可以单独在方法上使用 public List<Item> getItems() { // 返回项目列表 }
}