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

超实用!Spring Boot 常用注解详解与应用场景

目录

一、Web MVC 开发时,对于三层的类注解

1.1 @Controller

1.2 @Service

1.3 @Repository

1.4 @Component

二、依赖注入的注解

2.1 @Autowired

2.2 @Resource

2.3 @Resource 与 @Autowired 的区别

2.3.1 实例讲解

2.4 @Value

2.5 @Data

三、Web 常用的注解

3.1 @RequestMapping

3.2 @RequestParam

3.2.1 语法

3.2.2 实例

3.3 @PathVariable

3.4 @RequestParam 和 @PathVariable 区别

3.5 @ResponseBody 和 @RequestBody

3.6 @RestController

3.7 @ControllerAdvice 和 @ExceptionHandler

四、Spring Boot 常用的注解

4.1 @SpringBootApplication

4.2 @EnableAutoConfiguration

4.3 @Configuration

4.4 @ComponentScan

五、AOP 常用的注解

5.1 @Aspect

5.2 @After

5.3 @Before

5.4 @Around

5.5 @Pointcut

六、测试常用的注解

6.1 @SpringBootTest

6.2 @Test

6.3 @RunWith

6.4 其他测试注解

七、其他常用注解

7.1 @Transactional

7.2 @Cacheable

7.3 @PropertySource

7.4 @Async

7.5 @EnableAsync

7.6 @EnableScheduling

7.7 @Scheduled


一、Web MVC 开发时,对于三层的类注解

1.1 @Controller

@Controller 注解用于标识一个类是 Spring MVC 控制器,处理用户请求并返回相应的视图。

@Controller
public class MyController {// Controller methods
}

1.2 @Service

@Service 注解用于标识一个类是业务层组件,通常包含了业务逻辑的实现。

@Service
public class MyService {// Service methods
}

1.3 @Repository

@Repository 注解用于标识一个类是数据访问层组件,通常用于对数据库进行操作

@Repository
public class MyRepository {// Data access methods
}

1.4 @Component

@Component 是一个通用的组件标识,可以用于标识任何层次的组件,但通常在没有更明确的角色时使用。

@Component
public class MyComponent {// Class implementation
}

二、依赖注入的注解

2.1 @Autowired

@Autowired 注解用于自动装配 Bean,可以用在字段、构造器、方法上

@Service
public class MyService {@Autowiredprivate MyRepository myRepository;
}

2.2 @Resource

@Resource 注解也用于依赖注入,通常用在字段上,可以指定要注入的 Bean 的名称

@Service
public class MyService {@Resource(name = "myRepository")private MyRepository myRepository;
}

2.3 @Resource@Autowired 的区别

  • @Autowired 是 Spring 提供的注解,按照类型进行注入。
  • @Resource 是 JavaEE 提供的注解,按照名称进行注入。在 Spring 中也可以使用,并且支持指定名称。
2.3.1 实例讲解

新建 Animal 接口类,以及两个实现类 CatDog

public interface Animal {String makeSound();
}@Component
public class Cat implements Animal {@Overridepublic String makeSound() {return "Meow";}
}@Component
public class Dog implements Animal {@Overridepublic String makeSound() {return "Woof";}
}

编写测试用例:

@Service
public class AnimalService {@Autowiredprivate Animal cat;@Resource(name = "dog")private Animal dog;public String getCatSound() {return cat.makeSound();}public String getDogSound() {return dog.makeSound();}
}

2.4 @Value

@Value 注解用于从配置文件中读取值,并注入到属性中。

@Service
public class MyService {@Value("${app.message}")private String message;
}

2.5 @Data

@Data 是 Lombok 提供的注解,用于自动生成 Getter、Setter、toString 等方法。

@Data
public class MyData {private String name;private int age;
}

三、Web 常用的注解

3.1 @RequestMapping

@RequestMapping 注解用于映射请求路径,可以用在类和方法上。

@Controller
@RequestMapping("/api")
public class MyController {@GetMapping("/hello")public String hello() {return "Hello, Spring!";}
}

3.2 @RequestParam

@RequestParam 注解用于获取请求参数的值。

3.2.1 语法
@RequestParam(name = "paramName", required = true, defaultValue = "default")
3.2.2 实例
@GetMapping("/greet")
public String greet(@RequestParam(name = "name", required = false, defaultValue = "Guest") String name) {return "Hello, " + name + "!";
}

3.3 @PathVariable

@PathVariable 注解用于从 URI 中获取模板变量的值。

@GetMapping("/user/{id}")
public String getUserById(@PathVariable Long id) {// Retrieve user by ID
}

3.4 @RequestParam@PathVariable 区别

  • @RequestParam 用于获取请求参数。
  • @PathVariable 用于获取 URI 中的模板变量。

3.5 @ResponseBody@RequestBody

  • @ResponseBody 注解用于将方法的返回值直接写入 HTTP 响应体中。
  • @RequestBody 注解用于从 HTTP 请求体中读取数据。

3.6 @RestController

@RestController 注解相当于 @Controller@ResponseBody 的组合,用于标识 RESTful 风格的控制器。

@RestController
@RequestMapping("/api")
public class MyRestController {@GetMapping("/hello")public String hello() {return "Hello, Spring!";}
}

3.7 @ControllerAdvice@ExceptionHandler

@ControllerAdvice 注解用于全局处理异常,@ExceptionHandler 用于定义处理特定异常的方法。

@ControllerAdvice
public class GlobalExceptionHandler {@ExceptionHandler(Exception.class)public ResponseEntity<String> handleException(Exception e) {return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Internal Server Error");}
}

四、Spring Boot 常用的注解

4.1 @SpringBootApplication

@SpringBootApplication 是一个复合注解,包含了 @SpringBootConfiguration@EnableAutoConfiguration@ComponentScan

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

4.2 @EnableAutoConfiguration

@EnableAutoConfiguration 注解用于开启 Spring Boot 的自动配置机制。

4.3 @Configuration

@Configuration 注解用于定义配置类,替代传统的 XML 配置文件。

@Configuration
public class MyConfig {@Beanpublic MyBean myBean() {return new MyBean();}
}

4.4 @ComponentScan

@ComponentScan 注解用于配置组件扫描的基础包。

@SpringBootApplication
@ComponentScan(basePackages = "com.example")
public class MyApplication {public static void main(String[] args) {SpringApplication.run(MyApplication.class, args);}
}

五、AOP 常用的注解

5.1 @Aspect

@Aspect 注解用于定义切面类,通常与其他注解一起使用。

@Aspect
@Component
public class MyAspect {// Aspect methods
}

5.2 @After

@After 注解用于定义后置通知,方法在目标方法执行后执行。

@After("execution(* com.example.service.*.*(..))")
public void afterMethod() {// After advice
}

5.3 @Before

@Before 注解用于定义前置通知,方法在目标方法执行前执行

@Before("execution(* com.example.service.*.*(..))")
public void beforeMethod() {// Before advice
}

5.4 @Around

@Around 注解用于定义环绕通知,方法可以控制目标方法的执行。

@Around("execution(* com.example.service.*.*(..))")
public Object aroundMethod(ProceedingJoinPoint joinPoint) throws Throwable {// Before adviceObject result = joinPoint.proceed(); // Proceed to the target method// After advicereturn result;
}

5.5 @Pointcut

@Pointcut 注解用于定义切点,将切点表达式提取出来,供多个通知共享。

@Pointcut("execution(* com.example.service.*.*(..))")
public void serviceMethods() {// Pointcut expression
}

六、测试常用的注解

6.1 @SpringBootTest

@SpringBootTest 注解用于启动 Spring Boot 应用程序的测试。

@SpringBootTest
public class MyApplicationTests {// Test methods
}

6.2 @Test

@Test 注解用于标识测试方法。

@Test
public void myTestMethod() {// Test method
}

6.3 @RunWith

@RunWith 注解用于指定运行测试的类。

@RunWith(SpringRunner.class)
@SpringBootTest
public class MyApplicationTests {// Test methods
}

6.4 其他测试注解

  • @Before: 在测试方法之前执行。
  • @After: 在测试方法之后执行。
  • @BeforeClass: 在类加载时执行一次。
  • @AfterClass: 在类卸载时执行一次。

七、其他常用注解

7.1 @Transactional

@Transactional 注解用于声明事务,通常用在方法或类上。

@Service
@Transactional
public class MyTransactionalService {// Transactional methods
}

7.2 @Cacheable

@Cacheable 注解用于声明方法的结果可以被缓存。

@Service
public class MyCachingService {@Cacheable("myCache")public String getCachedData(String key) {// Method implementation}
}

7.3 @PropertySource

@PropertySource 注解用于引入外部的属性文件。

@Configuration
@PropertySource("classpath:my.properties")
public class MyConfig {// Configuration methods
}

7.4 @Async

@Async 注解用于声明异步方法,通常用在方法上。

@Service
public class MyAsyncService {@Asyncpublic void asyncMethod() {// Asynchronous method implementation}
}

7.5 @EnableAsync

@EnableAsync 注解用于开启异步方法的支持。

@Configuration
@EnableAsync
public class MyConfig {// Configuration methods
}

7.6 @EnableScheduling

@EnableScheduling 注解用于开启计划任务的支持。

@Configuration
@EnableScheduling
public class MyConfig {// Configuration methods
}

7.7 @Scheduled

@Scheduled 注解用于定义计划任务的执行时间。

@Service
public class MyScheduledService {@Scheduled(cron = "0 0 12 * * ?") // Run every day at 12 PMpublic void scheduledMethod() {// Scheduled method implementation}
}

以上几乎涵盖了所有springBoot和springFramework的常见注解,博客整体框架参考学习Spring Boot 注解,这一篇就够了(附带部分注解实例讲解)_springboot注解 举例-CSDN博客

相关文章:

超实用!Spring Boot 常用注解详解与应用场景

目录 一、Web MVC 开发时&#xff0c;对于三层的类注解 1.1 Controller 1.2 Service 1.3 Repository 1.4 Component 二、依赖注入的注解 2.1 Autowired 2.2 Resource 2.3 Resource 与 Autowired 的区别 2.3.1 实例讲解 2.4 Value 2.5 Data 三、Web 常用的注解 3.1…...

【古月居《ros入门21讲》学习笔记】11_客户端Client的编程实现

目录 说明&#xff1a; 1. 服务模型 2. 实现过程&#xff08;C&#xff09; 创建功能包 创建客户端代码&#xff08;C&#xff09; 配置客户端代码编译规则 编译 运行 3. 实现过程&#xff08;Python&#xff09; 创建客户端代码&#xff08;Python&#xff09; 运行…...

小程序和Vue写法的区别主要有什么不同

1.语法不同&#xff1a;小程序使用的是WXML、WXSS和JS&#xff0c;而Vue使用的是HTML、CSS和JSX。 2.数据绑定方式不同&#xff1a;小程序使用的是双向数据绑定&#xff0c;而Vue使用的是单向数据流。 1&#xff09;在小程序中需要使用e.currentTarget.dataset.*的方式获取&…...

Flutter之MQTT使用

1.添加依赖: 首先&#xff0c;需要在Flutter项目的​​pubspec.yaml​​​文件中添加​​mqtt_client​​依赖。 dependencies:#https://pub.dev/packages/mqtt_clientmqtt_client: ^10.0.02.创建MQTT客户端并连接到MQTT服务器:2.创建一个MQTT客户端实例来进行连接和通信 Fu…...

vr红色教育虚拟展馆全景制作提升单位品牌形象

720全景展馆编辑平台以其独特的优势&#xff0c;为展览行业带来了革命性的变革。这种创新的技术应用为参展商提供了更高效、更便捷、更全面的展示解决方案&#xff0c;进一步提升了展览行业的水平和影响力。 一、提升展示效果&#xff0c;增强品牌形象 720全景展馆编辑平台通过…...

【Spring】Spring是什么?

文章目录 前言什么是Spring什么是容器什么是 IoC传统程序开发控制反转式程序开发理解Spring IoCDI Spring帮助网站 前言 前面我们学习了 servlet 的相关知识&#xff0c;但是呢&#xff1f;使用 servlet 进行网站的开发步骤还是比较麻烦的&#xff0c;而我们本身程序员就属于是…...

事件循环机制及常见面试题

借鉴&#xff1a; 《Javascript 忍者秘籍》第二版&#xff0c;事件循环篇 面试 | JS 事件循环 event loop 经典面试题含答案 - 知乎 (zhihu.com) 概念 主栈队列就是一个宏任务&#xff0c;每一个宏任务执行完就会执行宏任务中的微任务&#xff0c;直到微任务全部都执行完&a…...

智能监控平台/视频共享融合系统EasyCVR接入RTSP协议视频流无法播放原因是什么?

视频集中存储/云存储/视频监控管理平台EasyCVR能在复杂的网络环境中&#xff0c;将分散的各类视频资源进行统一汇聚、整合、集中管理&#xff0c;实现视频资源的鉴权管理、按需调阅、全网分发、智能分析等。AI智能/大数据视频分析EasyCVR平台已经广泛应用在工地、工厂、园区、楼…...

c# statusStrip 显示电脑主机名、IP地址、MAC地址

控件&#xff1a; ToolStripStatusLabel 主机名&#xff1a; Dns.GetHostName() IP地址&#xff1a; Dns.GetHostAddresses(Dns.GetHostName())[0].ToString() 当前程序的版本&#xff1a; Assembly.GetExecutingAssembly().GetName().Version.ToString() 获取系统版本 …...

Cesium.CustomShader颜色值显示错误

官方示例&#xff1a; Cesium Sandcastle 测试过程&#xff1a; 1、修改示例&#xff0c;把customshader中的fragmentShaderText替换为如下代码 void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) {//注意&#xff1a;下述颜色的b值是0.1&#x…...

XSLVGL2.0 User Manual 页面管理器(v2.0)

XSLVGL2.0 开发手册 XSLVGL2.0 User Manual 页面管理器 1、概述2、特性3、APIs3.1、xs_page_init3.2、xs_page_wait_inited3.3、xs_page_exit3.4、xs_page_acquire3.5、xs_page_release3.6、xs_page_set_bootlogo3.7、xs_page_setup_clear_finish3.8、xs_page_setup_is_finish…...

论文学习-Attention Is All You Need

Attention Is All You Need 目前暂时不会用到&#xff0c;大概了解一下即可。 Recurrent model 序列化的计算方式&#xff0c;难以并行&#xff0c;随着序列的增长&#xff0c;以前的记忆会逐渐丢失。而Attention机制可以观察到句子中所有的信息&#xff0c;不受距离影响&…...

Springboot 使用 RabbitMq 延迟插件 实现订单到期未支付取消订单、设置提醒消息

示例业务场景&#xff1a; 场景1&#xff1a;客户下单后&#xff0c;15分钟内未支付取消订单&#xff01; 场景2&#xff1a;客户下单支付成功后&#xff0c;5分钟内商家未处理订单&#xff0c;需要推送一条消息提醒商家。如依旧未处理&#xff0c;则需要每隔2分钟消息提醒一下…...

Linux安装Tesseract-OCR(操作系统CentOS)

Linux安装Tesseract-OCR 第一步&#xff0c;安装依赖第二步&#xff0c;下载安装包第三步&#xff0c;安装leptonica库第四步&#xff0c;安装tesseract第五步&#xff0c;添加语言包第六步&#xff0c;测试 第一步&#xff0c;安装依赖 sudo yum install libpng-devel rpm -q…...

pair和typedef

文章目录 一、pair用法1.2、pair的创建和初始化1.3、pair对象的操作1.4、(make_pair)生成新的pair对象1.5、通过tie获取pair元素值 2、typedef2.1、什么是typedef2.2、typedef用法2.2.1、对于数据类型使用例如&#xff1a;2.2.2、对于指针的使用例如2.2.3、对于结构体的使用 2.…...

rdf-file:分布式环境下的文件处理

一&#xff1a;简介 数据量大了以后&#xff0c;单机解析或者生成文件的效率就很低&#xff0c;需要通过集群处理&#xff1a; 机构过来的文件&#xff1a;我们先对文件进行分片&#xff0c;在利用集群集群处理分片文件。给机构文件&#xff1a;分库分表数据&#xff0c;每个…...

Maven下载与安装教程

一、下载 Maven 进入 Maven 官网&#xff1a;maven.apache.org/download.cgi 选择 .zip 文件下载&#xff0c;最新版本是 3.9.5 二、安装 Maven 将 .zip 文件解压到没有中文没有空格的路径下。例如下图&#xff0c;在创建一个repository的空文件夹在他的下面&#xff0c;用于…...

C++(20):通过starts_with/ends_with检查字符串

C20提供了starts_with用于检查字符串是否以某个字符串开始&#xff0c;ends_with用于检查是否以某个字符串结束&#xff1a; #include <iostream> #include <string> using namespace std;int main() {string str "hello and 88";cout<<str.star…...

YOLOv8+Nanodet强强联合改进标签分配:使用NanoDet动态标签分配策略,同时集成VFL全新损失,来打造新颖YOLOv8检测器

💡本篇内容:YOLOv8+Nanodet强强联合改进标签分配:使用NanoDet动态标签分配策略,同时集成VFL全新损失,来打造新颖YOLOv8检测器 💡🚀🚀🚀本博客 YOLO系列 + 改进NanoDet模型的动态标签分配策略源代码改进 💡一篇博客集成多种创新点改进:VFL损失函数 + Nanodet…...

base64字符串转成file

分割base64字符串&#xff0c;获取base64的格式和ASCII字符串&#xff1b;使用atob()方法将base64中的ASCII字符串解码成二进制数据"字符串"&#xff1b;将二进制数据按位放入8 位无符号整型数组中适用new File()方法将ArrayBuffer转换成file对象 const base64 &qu…...

使用docker在3台服务器上搭建基于redis 6.x的一主两从三台均是哨兵模式

一、环境及版本说明 如果服务器已经安装了docker,则忽略此步骤,如果没有安装,则可以按照一下方式安装: 1. 在线安装(有互联网环境): 请看我这篇文章 传送阵>> 点我查看 2. 离线安装(内网环境):请看我这篇文章 传送阵>> 点我查看 说明&#xff1a;假设每台服务器已…...

Python爬虫实战:研究MechanicalSoup库相关技术

一、MechanicalSoup 库概述 1.1 库简介 MechanicalSoup 是一个 Python 库,专为自动化交互网站而设计。它结合了 requests 的 HTTP 请求能力和 BeautifulSoup 的 HTML 解析能力,提供了直观的 API,让我们可以像人类用户一样浏览网页、填写表单和提交请求。 1.2 主要功能特点…...

Chapter03-Authentication vulnerabilities

文章目录 1. 身份验证简介1.1 What is authentication1.2 difference between authentication and authorization1.3 身份验证机制失效的原因1.4 身份验证机制失效的影响 2. 基于登录功能的漏洞2.1 密码爆破2.2 用户名枚举2.3 有缺陷的暴力破解防护2.3.1 如果用户登录尝试失败次…...

在软件开发中正确使用MySQL日期时间类型的深度解析

在日常软件开发场景中&#xff0c;时间信息的存储是底层且核心的需求。从金融交易的精确记账时间、用户操作的行为日志&#xff0c;到供应链系统的物流节点时间戳&#xff0c;时间数据的准确性直接决定业务逻辑的可靠性。MySQL作为主流关系型数据库&#xff0c;其日期时间类型的…...

基于距离变化能量开销动态调整的WSN低功耗拓扑控制开销算法matlab仿真

目录 1.程序功能描述 2.测试软件版本以及运行结果展示 3.核心程序 4.算法仿真参数 5.算法理论概述 6.参考文献 7.完整程序 1.程序功能描述 通过动态调整节点通信的能量开销&#xff0c;平衡网络负载&#xff0c;延长WSN生命周期。具体通过建立基于距离的能量消耗模型&am…...

在鸿蒙HarmonyOS 5中实现抖音风格的点赞功能

下面我将详细介绍如何使用HarmonyOS SDK在HarmonyOS 5中实现类似抖音的点赞功能&#xff0c;包括动画效果、数据同步和交互优化。 1. 基础点赞功能实现 1.1 创建数据模型 // VideoModel.ets export class VideoModel {id: string "";title: string ""…...

算法岗面试经验分享-大模型篇

文章目录 A 基础语言模型A.1 TransformerA.2 Bert B 大语言模型结构B.1 GPTB.2 LLamaB.3 ChatGLMB.4 Qwen C 大语言模型微调C.1 Fine-tuningC.2 Adapter-tuningC.3 Prefix-tuningC.4 P-tuningC.5 LoRA A 基础语言模型 A.1 Transformer &#xff08;1&#xff09;资源 论文&a…...

C/C++ 中附加包含目录、附加库目录与附加依赖项详解

在 C/C 编程的编译和链接过程中&#xff0c;附加包含目录、附加库目录和附加依赖项是三个至关重要的设置&#xff0c;它们相互配合&#xff0c;确保程序能够正确引用外部资源并顺利构建。虽然在学习过程中&#xff0c;这些概念容易让人混淆&#xff0c;但深入理解它们的作用和联…...

Python+ZeroMQ实战:智能车辆状态监控与模拟模式自动切换

目录 关键点 技术实现1 技术实现2 摘要&#xff1a; 本文将介绍如何利用Python和ZeroMQ消息队列构建一个智能车辆状态监控系统。系统能够根据时间策略自动切换驾驶模式&#xff08;自动驾驶、人工驾驶、远程驾驶、主动安全&#xff09;&#xff0c;并通过实时消息推送更新车…...

Golang——6、指针和结构体

指针和结构体 1、指针1.1、指针地址和指针类型1.2、指针取值1.3、new和make 2、结构体2.1、type关键字的使用2.2、结构体的定义和初始化2.3、结构体方法和接收者2.4、给任意类型添加方法2.5、结构体的匿名字段2.6、嵌套结构体2.7、嵌套匿名结构体2.8、结构体的继承 3、结构体与…...