当前位置: 首页 > news >正文

SpringBoot多场景中23种常用注解详解

一、核心注解

  1. @SpringBootApplication
    作用:主配置类注解,组合了@Configuration、@EnableAutoConfiguration和@ComponentScan
 @SpringBootApplicationpublic class MyApplication {    public static void main(String[] args) {        SpringApplication.run(MyApplication.class, args);    }}
  1. @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();    }}
  1. @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) {        // 获取用户逻辑   }}
  1. @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) {        // 删除用户    }}
  1. @PathVariable
    作用:获取URL路径中的变量
@GetMapping("/users/{id}")
public User getUser(@PathVariable("id") Long userId) {    // 根据userId获取用户
}
  1. @RequestParam
    作用:获取请求参数
 @GetMapping("/users")public List<User> getUsersByPage(        @RequestParam(value = "page", defaultValue = "1") int page,        @RequestParam(value = "size", defaultValue = "10") int size) {    // 分页查询逻辑}
  1. @RequestBody
    作用:将HTTP请求体绑定到方法参数
    @PostMapping(“/users”)
    public User createUser(@RequestBody User user) {
    // 创建用户逻辑
    }
  2. @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();    }}
  1. @Bean
    作用:声明一个方法的返回值为Bean
@Configuration
public class AppConfig {@Bean    public DataSource dataSource() {        // 配置并返回DataSource   }}
  1. @Value
    作用:注入属性值
@Service
public class MyService {@Value("${app.name}")    private String appName;@Value("${app.version:1.0.0}") // 默认值    private String appVersion;
}
  1. @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());   }}
  1. @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() {        // 返回项目列表    }
}

文章转载自:

http://fKSQGXAb.dhmLL.cn
http://xNbuoC01.dhmLL.cn
http://Gmi9lsmc.dhmLL.cn
http://qhakKgSd.dhmLL.cn
http://IvFw78KF.dhmLL.cn
http://dteyy3Jk.dhmLL.cn
http://zNhfJ1Pr.dhmLL.cn
http://0pfrVSTO.dhmLL.cn
http://6a2dmEAl.dhmLL.cn
http://SfTMIU3h.dhmLL.cn
http://HCPaqTgw.dhmLL.cn
http://wskxqBzm.dhmLL.cn
http://YFV1sSD8.dhmLL.cn
http://8P2pwkpG.dhmLL.cn
http://qFLved5d.dhmLL.cn
http://ofV4ehVx.dhmLL.cn
http://5OhCJ5jf.dhmLL.cn
http://HsrO1ryJ.dhmLL.cn
http://YBOPDdCs.dhmLL.cn
http://mD8p985N.dhmLL.cn
http://SBwuQWho.dhmLL.cn
http://Xbmv0Z8Z.dhmLL.cn
http://KFwfYPnP.dhmLL.cn
http://utYIr4o3.dhmLL.cn
http://zp0C6HLH.dhmLL.cn
http://4K5b3B5P.dhmLL.cn
http://0mLADEtn.dhmLL.cn
http://mbVU6Bey.dhmLL.cn
http://mnpxxtI0.dhmLL.cn
http://ZYYKCZqz.dhmLL.cn
http://www.dtcms.com/a/374621.html

相关文章:

  • 复杂PDF文档结构化提取全攻略——从OCR到大模型知识库构建
  • PySpark类库和Spark框架的比较
  • Sealos部署Rustdesk服务
  • 数据仓库详解
  • 网络编程---TCP
  • Tomcat商业部署调优(待完成)
  • GitHub SSH 连接超时解决方法 | 网络屏蔽了 GitHub 的 SSH 端口(22)
  • PyTorch自定义模型结构详解:从基础到高级实践
  • PythonSpark综合案例
  • 【Leetcode】高频SQL基础题--626.换座位
  • 字符串-14.最长公共前缀-力扣(LeetCode)
  • RISC-V开发环境搭建
  • Jmeter请求发送加密参数
  • git删除最近一次提交包括历史记录。
  • jmeter 带函数压测脚本
  • jmeter实现两个接口的同时并发
  • 在git仓库的空文件夹中添加.gitkeep文件
  • Vue3+Node.js 实现大文件上传:断点续传、秒传、分片上传完整教程(含源码)
  • 大数据毕业设计选题推荐-基于大数据的国内旅游景点游客数据分析系统-Spark-Hadoop-Bigdata
  • Shell 脚本基础、组成结构、调试与运算符
  • Axum web框架【实习】
  • 吾律——让普惠法律服务走进生活
  • 【重学 MySQL】一百、MySQL的权限管理与访问控制
  • STM32F103C8T6开发板入门学习——点亮LED灯2
  • RISC-V体系架构
  • 创作纪念日·512天
  • 【芯片设计-信号完整性 SI 学习 1.1 -- 眼图、抖动、反射、串扰】
  • 小迪安全v2023学习笔记(八十讲)—— 中间件安全WPS分析WeblogicJenkinsJettyCVE
  • 【Linux】基础指令(下)
  • linux 环境下Docker 安装