Spring Spring Boot 常用注解整理

Spring & Spring Boot 常用注解整理

      • 先理解核心概念:什么是注解(Annotation)?
      • 第一部分:IOC(控制反轉)和 DI(依賴注入)
        • 1. @Component
        • 2. @Service, @Repository, @Controller
        • 3. @Autowired
        • 4. @Qualifier
      • 第二部分:Spring MVC(處理 HTTP 請求)
        • 1. @RestController vs @Controller
        • 2. @GetMapping / @PostMapping
        • 3. @PathVariable 和 @RequestParam
      • 第三部分:配置相關注解
        • 1. @Configuration 和 @Bean
        • 2. @Value
      • 第四部分:Spring Boot 核心注解
        • @SpringBootApplication
      • 第五部分:數據庫和事務
        • 1. @Entity 和 @Id
        • 2. @Transactional
      • 第六部分:AOP(面向切面編程)
        • 1. @Aspect 和 @Before
      • 總結:注解的核心作用

先理解核心概念:什么是注解(Annotation)?

類比:注解就像代碼里的“便利貼”,用來告訴 Spring 框架:“這個類/方法/變量有什么特殊用途”。
作用:簡化配置,讓框架自動幫你處理一些事情(比如創建對象、管理依賴、處理請求等)。

第一部分:IOC(控制反轉)和 DI(依賴注入)

核心思想:把對象的創建和管理交給 Spring 容器,而不是自己手動 new 對象。

注解說明示例
@Component通用組件標記,被掃描的類會納入 Spring 容器管理@Component public class MyComponent { ... }
@Service標記服務層組件,屬于@Component的特化形式@Service public class UserService { ... }
@Repository標記數據訪問層組件(DAO層),具有數據庫異常轉譯功能@Repository public class UserDao { ... }
@Controller標記控制器組件(Web層)@Controller public class UserController { ... }
@Autowired自動注入依賴,默認按類型匹配@Autowired private UserService userService;
@Qualifier按名稱指定注入的 Bean@Autowired @Qualifier("userServiceImplA") private UserService service;
@Primary標記首選的 Bean(存在多個同類型 Bean 時優先注入)@Bean @Primary public DataSource primaryDataSource() { ... }
@Scope定義 Bean 的作用域(singleton/prototype等)@Component @Scope("prototype") public class MyPrototypeBean { ... }
1. @Component

作用:告訴 Spring:“這個類交給你管理,我需要的時候找你要實例”。
代碼示例

@Component  // 貼上這個標簽,Spring 就會自動創建 MyComponent 的實例(Bean)
public class MyComponent {public void hello() {System.out.println("Hello from MyComponent!");}
}

使用場景:通用的工具類、第三方庫的適配類等。


2. @Service, @Repository, @Controller

本質:它們都是 @Component 的“馬甲”,用途相同,只是名字不同,為了代碼可讀性。

  • @Service:標記業務邏輯層(如處理用戶注冊、訂單支付)。
  • @Repository:標記數據訪問層(如操作數據庫)。
  • @Controller:標記 Web 控制器(處理 HTTP 請求)。

代碼對比

@Service
public class UserService {  // 業務邏輯層public void registerUser(String name) { ... }
}@Repository
public class UserDao {  // 數據訪問層public User findUserById(Long id) { ... }
}@Controller
public class UserController {  // 處理 HTTP 請求@GetMapping("/users")public String listUsers() { ... }
}

3. @Autowired

作用:讓 Spring 自動幫你“注入”依賴的 Bean(類似找人借東西,不用自己造)。
代碼示例

@Service
public class UserService {@Autowired  // Spring 會自動找一個 UserDao 的 Bean 注入到這里private UserDao userDao;public User findUser(Long id) {return userDao.findUserById(id);  // 直接使用 userDao,不需要 new UserDao()}
}

原理:Spring 會在容器中查找匹配類型的 Bean,自動賦值給 userDao


4. @Qualifier

問題場景:如果有多個同類型的 Bean,Spring 不知道注入哪一個。
解決:用 @Qualifier 指定 Bean 的名字。

代碼示例

// 定義兩個數據源
@Component("mysqlDataSource")
public class MySQLDataSource implements DataSource { ... }@Component("postgresDataSource")
public class PostgresDataSource implements DataSource { ... }// 使用時指定名稱
@Service
public class DataService {@Autowired@Qualifier("mysqlDataSource")  // 明確告訴 Spring 注入名為 "mysqlDataSource" 的 Beanprivate DataSource dataSource;
}

第二部分:Spring MVC(處理 HTTP 請求)

注解說明示例
@RestController組合注解(@Controller + @ResponseBody),用于 REST API@RestController public class ApiController { ... }
@RequestMapping映射 HTTP 請求路徑,可指定 method@RequestMapping(value="/users", method=RequestMethod.GET)
@GetMapping簡化 GET 請求映射(同理有@PostMapping@PutMapping等)@GetMapping("/{id}") public User getUser(@PathVariable Long id)
@PathVariable綁定 URL 路徑中的變量@GetMapping("/users/{id}") public User getById(@PathVariable Long id)
@RequestParam綁定請求參數(支持默認值、是否必傳等)@GetMapping("/search") public List<User> search(@RequestParam(defaultValue = "") String keyword)
@RequestBody將請求體內容反序列化為 Java 對象(如 JSON)@PostMapping public User create(@RequestBody User user) { ... }
@ResponseBody將方法返回值序列化為響應體(如 JSON)已內置在@RestController
@ExceptionHandler處理控制器內的特定異常@ExceptionHandler(UserNotFoundException.class) public ResponseEntity<String> handleException() { ... }
@CrossOrigin允許跨域請求@CrossOrigin(origins = "http://example.com")
1. @RestController vs @Controller
  • @Controller:傳統 MVC 控制器,返回視圖(如 JSP 頁面)。
  • @RestController:專門用于 REST API,直接返回 JSON 數據(內部包含 @ResponseBody)。

代碼對比

// 傳統 Controller(返回視圖名,由模板引擎渲染)
@Controller
public class OldController {@GetMapping("/hello")public String hello() {return "hello-page";  // 對應 src/main/resources/templates/hello-page.html}
}// REST Controller(返回 JSON)
@RestController
public class ApiController {@GetMapping("/user")public User getUser() {return new User(1, "Alice");  // 自動轉換為 JSON:{ "id": 1, "name": "Alice" }}
}

2. @GetMapping / @PostMapping

作用:簡化 HTTP 請求映射,替代 @RequestMapping(method=RequestMethod.GET)

代碼示例

@RestController
public class UserController {// 處理 GET 請求:http://localhost:8080/users@GetMapping("/users")public List<User> listUsers() {return userService.getAllUsers();}// 處理 POST 請求:http://localhost:8080/users@PostMapping("/users")public User createUser(@RequestBody User user) {  // @RequestBody 表示接收 JSON 數據return userService.saveUser(user);}
}

3. @PathVariable 和 @RequestParam
  • @PathVariable:從 URL 路徑中獲取變量(如 /users/123 中的 123)。
  • @RequestParam:從 URL 參數中獲取值(如 /search?keyword=java 中的 keyword)。

代碼示例

@GetMapping("/users/{id}")  // URL 模板:{id} 是占位符
public User getUserById(@PathVariable Long id) {  // 獲取路徑中的 idreturn userService.findById(id);
}@GetMapping("/search")
public List<User> searchUsers(@RequestParam String keyword) {  // 獲取參數 ?keyword=xxxreturn userService.search(keyword);
}

第三部分:配置相關注解

注解說明示例
@Configuration標記類為配置類(替代 XML 配置文件)@Configuration public class AppConfig { ... }
@Bean聲明方法返回的對象作為 Bean 加入容器@Bean public DataSource dataSource() { return new HikariDataSource(); }
@Value注入配置文件中的值@Value("${db.url}") private String dbUrl;
@PropertySource加載指定 properties 文件@Configuration @PropertySource("classpath:custom.properties")
@ConfigurationProperties批量綁定配置文件屬性到對象(需配合@EnableConfigurationProperties@Component @ConfigurationProperties(prefix="app") public class AppConfig { private String name; ... }
@Profile指定 Bean 生效的環境@Bean @Profile("dev") public DataSource devDataSource() { ... }
1. @Configuration 和 @Bean

作用:替代 XML 配置文件,手動定義 Bean。

代碼示例

@Configuration  // 告訴 Spring:“這是一個配置類”
public class AppConfig {@Bean  // 這個方法返回的對象會被 Spring 管理public DataSource dataSource() {return new HikariDataSource();  // 手動創建一個數據源}
}

2. @Value

作用:從配置文件(如 application.properties)中讀取值。

示例

# application.properties
app.name=My Awesome App
database.url=jdbc:mysql://localhost:3306/mydb
@Component
public class AppConfig {@Value("${app.name}")  // 注入 app.name 的值private String appName;@Value("${database.url}")  // 注入數據庫 URLprivate String dbUrl;
}

第四部分:Spring Boot 核心注解

注解說明示例
@SpringBootApplication啟動類注解(包含@Configuration+@EnableAutoConfiguration+@ComponentScan@SpringBootApplication public class MyApp { public static void main(String[] args) { SpringApplication.run(MyApp.class, args); } }
@EnableAutoConfiguration啟用自動配置機制(通常已包含在@SpringBootApplication中)顯式使用:@SpringBootApplication @EnableAutoConfiguration
@ConditionalOnProperty根據配置屬性條件化創建 Bean@Bean @ConditionalOnProperty(name="feature.enabled", havingValue="true") public FeatureBean featureBean() { ... }
@SpringBootApplication

作用:標記啟動類,包含三個核心功能:

  1. @Configuration:這是一個配置類。
  2. @EnableAutoConfiguration:開啟自動配置(如自動配置數據庫連接池)。
  3. @ComponentScan:自動掃描當前包及子包下的組件(@Component, @Service 等)。

代碼示例

@SpringBootApplication  // 一切從這里開始
public class MyApplication {public static void main(String[] args) {SpringApplication.run(MyApplication.class, args);  // 啟動 Spring Boot 應用}
}

第五部分:數據庫和事務

注解說明示例
@Transactional聲明事務管理(可加在類或方法上)@Transactional public void updateUser(User user) { ... }
@EntityJPA 實體類標記@Entity public class User { @Id private Long id; ... }
@JpaRepositorySpring Data JPA 的倉庫接口public interface UserRepository extends JpaRepository<User, Long> { ... }
1. @Entity 和 @Id

作用:標記 JPA 實體類(對應數據庫表)和主鍵字段。

代碼示例

@Entity  // 告訴 Spring:“這是一個數據庫表對應的實體類”
public class User {@Id  // 標記為主鍵private Long id;private String name;// 省略 getter/setter
}

2. @Transactional

作用:聲明事務,確保方法內的數據庫操作要么全部成功,要么全部回滾。

代碼示例

@Service
public class OrderService {@Autowiredprivate OrderRepository orderRepository;@Transactional  // 開啟事務public void placeOrder(Order order) {orderRepository.save(order);  // 保存訂單// 如果這里拋出異常(如庫存不足),整個事務會回滾,訂單不會被保存}
}

第六部分:AOP(面向切面編程)

核心思想:在不修改原有代碼的情況下,統一處理日志、權限、事務等橫切關注點。

注解說明示例
@Aspect聲明切面類@Aspect @Component public class LoggingAspect { ... }
@Pointcut定義切入點表達式@Pointcut("execution(* com.example.service.*.*(..))") public void serviceMethods() {}
@Before前置通知@Before("serviceMethods()") public void logBefore(JoinPoint jp) { ... }
1. @Aspect 和 @Before

代碼示例

@Aspect   // 告訴 Spring:“這是一個切面類”
@Component
public class LoggingAspect {// 定義切入點:攔截所有 Service 層的方法@Pointcut("execution(* com.example.service.*.*(..))")public void serviceMethods() {}// 前置通知:在方法執行前打印日志@Before("serviceMethods()")public void logBefore(JoinPoint joinPoint) {String methodName = joinPoint.getSignature().getName();System.out.println("準備執行方法:" + methodName);}
}

總結:注解的核心作用

場景常用注解類比解釋
管理對象@Component, @Service告訴 Spring:“這個類歸你管!”
依賴注入@Autowired, @Qualifier告訴 Spring:“我需要這個,幫我拿!”
處理 HTTP 請求@RestController, @GetMapping告訴 Spring:“這個方法是處理某個 URL 的!”
讀取配置@Value, @ConfigurationProperties告訴 Spring:“把配置文件的值給我!”
事務管理@Transactional告訴 Spring:“這個方法要保證事務!”

在這里插入圖片描述

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/83200.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/83200.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/83200.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

AIGC與數字媒體實驗室解決方案分享

第1部分 概述 1.1 建設目標 1.深度融合AIGC技術&#xff0c;培養能夠駕馭新質生產力的數字媒體人才 通過引入前沿的AIGC技術&#xff0c;確保學生能夠接觸到最先進的人工智能應用。教學內容理論和實踐結合&#xff0c;讓學生在實際操作中熟練掌握AIGC工具&#xff0c;生成高…

訊聯云庫項目開發日志(二)AOP參數攔截

目錄 利用AOP實現參數攔截: 一、??HTTP請求進入Controller?&#xff08;發送郵件驗證碼&#xff09; 二、AOP切面觸發 1. 切面攔截&#xff08;GlobalOperactionAspect.class&#xff09; method.getAnnotation()?? null interceptor 判斷?? 2.參數校驗注解 3. 參…

用OBD部署OceanBase社區版的避坑指南

以下是用OBD黑屏部署 OceanBase社區版時容易碰到的幾個問題及解決思路&#xff0c;供大家參考。 一、 遇坑步驟&#xff1a;用yaml文件部署集群&#xff1a; obd cluster deploy obtest -c mini-single-example.yaml 報錯&#xff1a; Package oceanbase-ce-4.2.1.8-108000…

無錫哲訊科技:引領芯片封裝SAP系統的智能化革命

芯片封裝行業的數字化轉型 在全球半導體產業高速發展的今天&#xff0c;芯片封裝作為產業鏈的關鍵環節&#xff0c;直接影響著芯片的性能、可靠性和成本。隨著5G、人工智能、物聯網等技術的普及&#xff0c;市場對芯片的需求激增&#xff0c;封裝企業面臨著效率提升、良率優…

從海洋生物找靈感:造個機器人RoboPteropod,它能在水下干啥?

大家好&#xff01;在如今人類對水下環境探索不斷深入的時代&#xff0c;從水下考古到珊瑚礁考察&#xff0c;各種任務都離不開水下機器人的助力。但傳統水下機器人尺寸較大&#xff0c;在狹窄的水下空間施展不開。今天&#xff0c;我們就來認識一款受海洋小生物啟發而設計的仿…

區塊鏈blog1__合作與信任

&#x1f342;我們的世界 &#x1f33f;不是孤立的&#xff0c;而是網絡化的 如果是單獨孤立的系統&#xff0c;無需共識&#xff0c;而我們的社會是網絡結構&#xff0c;即結點間不是孤立的 &#x1f33f;網絡化的原因 而目前并未發現這樣的理想孤立系統&#xff0c;即現實中…

Linux服務之lvs+keepalived nginx+keepalived負載均衡實例解析

目錄 一.LVSKeepAlived高可用負載均衡集群的部署 二.NginxKeepAlived高可用負載均衡集群的部署 一.LVSKeepAlived高可用負載均衡集群的部署 實驗環境 主keepalived&#xff1a;192.168.181.10 lvs &#xff08;7-1&#xff09; 備keepalived&#xff1a;192.168.181.10…

50天50個小項目 (Vue3 + Tailwindcss V4) ? |搭建項目框架

&#x1f5a4; 一個專注于「Vue3 TailwindCSS」的 50 天極簡開發挑戰&#xff0c;探索組件邊界&#xff0c;打磨技術鋒芒。 &#x1f389; 歡迎來到 50 個小項目的第一天&#xff01;今天我們將從零開始搭建一個 Vue3 項目&#xff0c;并引入 Tailwind CSS v4&#xff0c;為后…

Android 中 網絡圖片加載庫 Glide 簡介

Glide 是一個功能強大且廣泛使用的圖片加載庫,適用于 Android 應用程序。它提供了簡單易用的 API,用于從網絡、本地存儲或資源中加載圖片,并支持圖片的緩存、轉換、占位圖、動畫等功能。 一、Glide 主要特點 簡單易用 提供簡潔的 API,一行代碼即可加載圖片。 支持多種數據…

07 web 自動化之 Unittest 應用:測試報告裝飾器斷言

文章目錄 一、常見的第三方庫結合 unittest 生產 html 格式測試報告1、HtmlTestRunner2、BeatifulReport 二、裝飾器 unittest.skip 強制跳過&條件跳過三、unittest的常用斷言方法 一、常見的第三方庫結合 unittest 生產 html 格式測試報告 1、HtmlTestRunner 官網下載 …

【Python 面向對象】

Python 的面向對象編程&#xff08;OOP&#xff09;通過類&#xff08;Class&#xff09;和對象&#xff08;Object&#xff09;實現代碼結構化&#xff0c;支持封裝、繼承和多態三大特性。以下是系統化指南&#xff1a; 一、類與對象基礎 1. 定義類 class Dog:# 類屬性&…

STM32F103_LL庫+寄存器學習筆記23 - PWM波形輸出及軟件方式調整周期與占空比

導言 脈寬調制&#xff08;PWM&#xff09;是 STM32 定時器最常用的輸出模式之一&#xff0c;廣泛應用于電機驅動、LED 調光、伺服控制和功率管理等場景。本篇文章將以 TIM5 為例&#xff0c;從寄存器層面深入剖析 PWM 輸出的原理與實現步驟。通過本篇博客&#xff0c;你不僅能…

堆(Heap)

1. 堆&#xff08;Heap&#xff09; 1.1. Python實現堆的插入、堆頂刪除和排序 class MaxHeap:def __init__(self):# 初始化空堆&#xff0c;使用列表表示self.heap []def insert(self, val):# 插入元素并執行上浮self.heap.append(val)self._sift_up(len(self.heap) - 1)de…

Spring類

BeanDefinition BeanDefinition表示Bean定義&#xff0c;BeanDefinition中存在很多屬性用來描述一個Bean的特點。比如&#xff1a; class&#xff0c;表示Bean類型scope&#xff0c;表示Bean作用域&#xff0c;單例或原型等lazyInit&#xff1a;表示Bean是否是懶加載initMeth…

在vue中this.$emit有哪些作用,事件監控具體含義,以及這些子組件能封裝哪些功能組件

this.$emit 的作用 this.$emit 的作用是觸發一個自定義事件&#xff0c;并將數據傳遞給父組件。父組件可以通過 v-on&#xff08;或 &#xff09;監聽這個事件&#xff0c;并在事件觸發時執行相應的處理函數。 this.content 的作用 this.content 是子組件的 props&#xff0…

前端流行框架Vue3教程:16. 組件事件配合`v-model`使用

組件事件配合v-model使用 如果是用戶輸入&#xff0c;我們希望在獲取數據的同時發送數據配合v-model 來使用&#xff0c;幫助理解組件間的通信和數據綁定。 &#x1f9e9; 第一步&#xff1a;創建子組件&#xff08;SearchComponent.vue&#xff09; 這個組件用于處理用戶的搜…

《Navicat之外的新選擇:實測支持國產數據庫的SQLynx核心功能解析》

數據庫工具生態的新變量 在數據庫管理工具領域&#xff0c;Navicat長期占據開發者心智。但隨著國產數據庫崛起和技術信創需求&#xff0c;開發者對工具的兼容性、輕量化和本土化適配提出了更高要求。近期體驗了一款名為SQLynx的國產數據庫管理工具&#xff08;麥聰旗下產品&am…

AgenticSeek開源的完全本地的 Manus AI。無需 API,享受一個自主代理,它可以思考、瀏覽 Web 和編碼,只需支付電費。

?一、軟件介紹 文末提供程序和源碼下載 AgenticSeek開源的完全本地的 Manus AI。無需 API&#xff0c;享受一個自主代理&#xff0c;它可以思考、瀏覽 Web 和編碼&#xff0c;只需支付電費。這款支持語音的 AI 助手是 Manus AI 的 100% 本地替代品 &#xff0c;可自主瀏覽網頁…

vue3.0的name屬性插件——vite-plugin-vue-setup-extend

安裝 這個由于是在開發環境下的一個插件 幫助我們支持name屬性 所以需要是-D npm i vite-plugin-vue-setup-extend -D在pasckjson中無法注釋每個插件的用處 可以在vscode中下載一個JsonComments這樣可以在json中添加注釋方便日后維護和查閱API 引入 在vite.config.js中 im…

Linux基礎 -- 在內存中使用chroot修復eMMC

Linux基礎 – 在內存中使用chroot修復eMMC 概述 本教程將介紹如何在Linux系統中&#xff0c;使用chroot在內存中構建一個臨時系統&#xff0c;并在不依賴原有系統的情況下修復eMMC&#xff08;如/dev/mmcblk2&#xff09;磁盤。該方法適用于嵌入式系統修復、磁盤清理以及離線…