SpringBoot 常用註解總結

核心註解

1. @SpringBootApplication

主要用於開啓自動配置,它也是一個組合註解,主要組合了 @SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan

2. @EnableAutoConfiguration

該註解組合了 @Import 註解,@Import 註解導入了 EnableAutoCofigurationImportSelector 類,它使用 SpringFactoriesLoader.loaderFactoryNames 方法把 spring-boot-autoconfigure.jar/META-INF/spring.factories 中的每一個 xxxAutoConfiguration 文件都加載到 IOC 容器,實現自動配置

3. @SpringBootConfiguration

@SpringBootConfiguration 註解繼承自 @Configuration,二者功能基本一致,標註當前類是配置類

4. @ComponentScan

自動掃描並加載符合條件的組件,如 @Component、@Controller、@Service、@Repository 等或者 bean 定義,最終將這些 Bean 加載到 IOC 容器


Bean 相關

1. @Controller

應用於控制層,DispatcherServlet 會自動掃描此註解的類,將 web 請求映射到註解 @RequestMapping 的方法上

2. @Service

應用於業務邏輯層

3. @Reponsitory

應用於數據訪問層(dao)

4. @Component

表示帶有該註解的類是一個組件,可被 SpringBoot 掃描並注入 IOC 容器

5. @Configuration

表示帶有該註解的類是一個配置類,通常與 @Bean 結合使用,@Configuration 繼承了 @Component,因此也能被 SpringBoot 掃描並處理

6. @Bean

@Configuration 註解標識的類,使用 @Bean 註解一個可返回 Bean 的方法,Spring 會將這個 Bean 對象放入 IOC 容器


依賴注入相關

1. @Autowired

可作用在屬性、方法和構造器,實現 Bean 的自動注入,默認根據類型注入

2. @Resource

作用同 @Autowired,默認通過名稱注入

3. @Qualifier

如果容器中有多個相同類型的 bean,僅僅靠 @Autowired 不足以讓 Spring 知道到底要注入哪個 bean,使用 @Qualifier 並指定名稱可以幫助確認注入哪個 bean

4. @Value

用於注入基本類型和 String 類型


WEB 相關

1. @RequestMapping

映射 web 請求,可以註解在類和方法上,@GetMapping 和 @PostMapping 是 @RequestMapping 的兩種特例,一個處理 get 請求,一個處理 post 請求

2. @RequestParam

獲取請求參數,示例如下:

// http://localhost:8080/api/test1?name=liu
@RequestMapping("/test1")
@ResponseBody
public String test1(@RequestParam("name")String name1){
    System.out.println(name1);
    return name1;
}

3. @PathVariable

獲取路徑參數,示例如下:

@RequestMapping(value = "user/{username}")
public String test(@PathVariable(value="username") String username) {
	return "user"+username;
}

4. @RequestBody

通過 HttpMessageConverter 讀取 Request Body 並反序列化爲 Object,比如直接以 String 接收前端傳過來的 json 數據

5. @ResponseBody

將返回值放在 response 體內,返回的是數據而不是頁面,在異步請求返回 json 數據時使用


AOP 相關

1. @Aspect

聲明一個切面

2. @PointCut

聲明切點,即定義攔截規則,確定有哪些方法會被切入

3. @Before

前置通知,在原方法前執行

4. @After

後置通知,在原方法後執行

5. @Around

環繞通知,原方法執行前執行一次,原方法執行後再執行一次


其他註解

1. @Transactional

聲明事務

2. @ControllerAdvice

作用在類上,繼承了 @Component,因此也能被 SpringBoot 掃描並處理,提供對 Controller 類的攔截功能,配合 @ExceptionHandler、@InitBinder、@ModelAttribute 等註解可實現全局異常處理,全局參數綁定,請求參數預處理等功能

3. @Async

作用在方法,表示這是一個異步方法

4. @EnableAsync

註解在配置類,開啓異步任務支持

5. @Scheduled

註解在方法,聲明該方法是計劃任務

6. @EnableScheduling

註解在配置類,開啓對計劃任務的支持

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章