1. 程式人生 > 其它 >Spring最常用的7大類註解

Spring最常用的7大類註解

隨著技術的更新迭代,Java5.0開始支援註解。而作為java中的領軍框架spring,自從更新了2.5版本之後也開始慢慢捨棄xml配置,更多使用註解來控制spring框架。
而spring的的註解那麼多,可能做java很多年,都用不上。這裡按照型別總結了這7種最常用的註解。

一. 核心註解

@Required
此註解用於bean的setter方法上。表示此屬性是必須的,必須在配置階段注入,否則會丟擲BeanInitializationExcepion。

@Autowired
此註解用於bean的field、setter方法以及構造方法上,顯式地宣告依賴。根據type來autowiring。

當在field上使用此註解,並且使用屬性來傳遞值時,Spring會自動把值賦給此field。也可以將此註解用於私有屬性(不推薦),如下。

  1. @Component

  2. publicclassUser{

  3. @Autowired

  4. privateAddress address;

  5. }

最經常的用法是將此註解用於settter上,這樣可以在setter方法中新增自定義程式碼。如下:

  1. @Component

  2. publicclassUser{

  3. privateAddress address;

  4. @AutoWired

  5. public setAddress(Address address) {

  6. // custom code

  7. this.address=address;

  8. }

  9. }

當在構造方法上使用此註解的時候,需要注意的一點就是一個類中只允許有一個構造方法使用此註解。此外,在Spring4.3後,如果一個類僅僅只有一個構造方法,那麼即使不使用此註解,那麼Spring也會自動注入相關的bean。如下:

  1. @Component

  2. publicclassUser{

  3. privateAddress address;

  4. publicUser(Address address) {

  5. this.address=address;

  6. }

  7. }

  8. <bean id="user"class="xx.User"/>

@Qualifier


此註解是和@Autowired一起使用的。使用此註解可以讓你對注入的過程有更多的控制。

@Qualifier可以被用在單個構造器或者方法的引數上。當上下文有幾個相同型別的bean, 使用@Autowired則無法區分要繫結的bean,此時可以使用@Qualifier來指定名稱。

  1. @Component

  2. publicclassUser{

  3. @Autowired

  4. @Qualifier("address1")

  5. privateAddress address;

  6. ...

  7. }

@Configuration
此註解用在class上來定義bean。其作用和xml配置檔案相同,表示此bean是一個Spring配置。此外,此類可以使用@Bean註解來初始化定義bean。

  1. @Configuartion

  2. publicclassSpringCoreConfig{

  3. @Bean

  4. publicAdminUser adminUser() {

  5. AdminUser adminUser = newAdminUser();

  6. return adminUser;

  7. }

  8. }

@ComponentScan
此註解一般和@Configuration註解一起使用,指定Spring掃描註解的package。如果沒有指定包,那麼預設會掃描此配置類所在的package。

@Lazy
此註解使用在Spring的元件類上。預設的,Spring中Bean的依賴一開始就被建立和配置。如果想要延遲初始化一個bean,那麼可以在此類上使用Lazy註解,表示此bean只有在第一次被使用的時候才會被建立和初始化。此註解也可以使用在被@Configuration註解的類上,表示其中所有被@Bean註解的方法都會延遲初始化。

@Value
此註解使用在欄位、構造器引數和方法引數上。@Value可以指定屬性取值的表示式,支援通過#{}使用SpringEL來取值,也支援使用${}來將屬性來源中(Properties檔案、本地環境變數、系統屬性等)的值注入到bean的屬性中。此註解值的注入發生在AutowiredAnnotationBeanPostProcessor類中。

二. Spring MVC和REST註解

@Controller
此註解使用在class上宣告此類是一個Spring controller,是@Component註解的一種具體形式。

@RequestMapping
此註解可以用在class和method上,用來對映web請求到某一個handler類或者handler方法上。當此註解用在Class上時,就創造了一個基礎url,其所有的方法上的@RequestMapping都是在此url之上的。

可以使用其method屬性來限制請求匹配的http method。

  1. @Controller

  2. @RequestMapping("/users")

  3. publicclassUserController{

  4. @RequestMapping(method = RequestMethod.GET)

  5. publicString getUserList() {

  6. return"users";

  7. }

  8. }

此外,Spring4.3之後引入了一系列@RequestMapping的變種。如下:

  • @GetMapping

  • @PostMapping

  • @PutMapping

  • @PatchMapping

  • @DeleteMapping

分別對應了相應method的RequestMapping配置。

@CookieValue
此註解用在@RequestMapping宣告的方法的引數上,可以把HTTP cookie中相應名稱的cookie繫結上去。

  1. @ReuestMapping("/cookieValue")

  2. publicvoid getCookieValue(@CookieValue("JSESSIONID") String cookie){

  3. }

cookie即http請求中name為JSESSIONID的cookie值。

@CrossOrigin
此註解用在class和method上用來支援跨域請求,是Spring 4.2後引入的。

  1. @CrossOrigin(maxAge = 3600)

  2. @RestController

  3. @RequestMapping("/users")

  4. publicclassAccountController{

  5. @CrossOrigin(origins = "http://xx.com")

  6. @RequestMapping("/login")

  7. publicResult userLogin() {

  8. // ...

  9. }

  10. }

@ExceptionHandler
此註解使用在方法級別,宣告對Exception的處理邏輯。可以指定目標Exception。

@InitBinder
此註解使用在方法上,宣告對WebDataBinder的初始化(繫結請求引數到JavaBean上的DataBinder)。在controller上使用此註解可以自定義請求引數的繫結。

@MatrixVariable
此註解使用在請求handler方法的引數上,Spring可以注入matrix url中相關的值。這裡的矩陣變數可以出現在url中的任何地方,變數之間用;分隔。如下:

  1. // GET /pets/42;q=11;r=22

  2. @RequestMapping(value = "/pets/{petId}")

  3. publicvoid findPet(@PathVariableString petId, @MatrixVariableint q) {

  4. // petId == 42

  5. // q == 11

  6. }

需要注意的是預設Spring mvc是不支援矩陣變數的,需要開啟。

  1. <mvc:annotation-drivenenable-matrix-variables="true"/>

註解配置則需要如下開啟:

  1. @Configuration

  2. publicclassWebConfigextendsWebMvcConfigurerAdapter{

  3. @Override

  4. publicvoid configurePathMatch(PathMatchConfigurer configurer) {

  5. UrlPathHelper urlPathHelper = newUrlPathHelper();

  6. urlPathHelper.setRemoveSemicolonContent(false);

  7. configurer.setUrlPathHelper(urlPathHelper);

  8. }

  9. }

@PathVariable
此註解使用在請求handler方法的引數上。@RequestMapping可以定義動態路徑,如:

  1. @RequestMapping("/users/{uid}")

可以使用@PathVariable將路徑中的引數繫結到請求方法引數上。

  1. @RequestMapping("/users/{uid}")

  2. publicString execute(@PathVariable("uid") String uid){

  3. }

  4. @RequestAttribute

此註解用在請求handler方法的引數上,用於將web請求中的屬性(request attributes,是伺服器放入的屬性值)繫結到方法引數上。

@RequestBody
此註解用在請求handler方法的引數上,用於將http請求的Body對映繫結到此引數上。HttpMessageConverter負責將物件轉換為http請求。

@RequestHeader
此註解用在請求handler方法的引數上,用於將http請求頭部的值繫結到引數上。

@RequestParam
此註解用在請求handler方法的引數上,用於將http請求引數的值繫結到引數上。

@RequestPart
此註解用在請求handler方法的引數上,用於將檔案之類的multipart繫結到引數上。

@ResponseBody
此註解用在請求handler方法上。和@RequestBody作用類似,用於將方法的返回物件直接輸出到http響應中。

@ResponseStatus
此註解用於方法和exception類上,宣告此方法或者異常類返回的http狀態碼。可以在Controller上使用此註解,這樣所有的@RequestMapping都會繼承。

@ControllerAdvice
此註解用於class上。前面說過可以對每一個controller宣告一個ExceptionMethod。這裡可以使用@ControllerAdvice來宣告一個類來統一對所有@RequestMapping方法來做@ExceptionHandler、@InitBinder以及@ModelAttribute處理。

@RestController
此註解用於class上,宣告此controller返回的不是一個檢視而是一個領域物件。其同時引入了@Controller和@ResponseBody兩個註解。

@RestControllerAdvice
此註解用於class上,同時引入了@ControllerAdvice和@ResponseBody兩個註解。

@SessionAttribute
此註解用於方法的引數上,用於將session中的屬性繫結到引數。

@SessionAttributes
此註解用於type級別,用於將JavaBean物件儲存到session中。一般和@ModelAttribute註解一起使用。如下:

  1. @ModelAttribute("user")

  2. publicPUser getUser() {}

  3. // controller和上面的程式碼在同一controller中

  4. @Controller

  5. @SeesionAttributes(value = "user", types = {

  6. User.class

  7. })

  8. publicclassUserController{}

三. Spring Boot註解

@EnableAutoConfiguration
此註解通常被用在主應用class上,告訴Spring Boot自動基於當前包新增Bean、對bean的屬性進行設定等。

@SpringBootApplication
此註解用在Spring Boot專案的應用主類上(此類需要在base package中)。使用了此註解的類首先會讓Spring Boot啟動對base package以及其sub-pacakage下的類進行component scan。

此註解同時添加了以下幾個註解:

  • @Configuration

  • @EnableAutoConfiguration

  • @ComponentScan

四. Stereotype註解

@Component
此註解使用在class上來宣告一個Spring元件(Bean), 將其加入到應用上下文中。

@Controller
前文已經提到過

@Service
此註解使用在class上,宣告此類是一個服務類,執行業務邏輯、計算、呼叫內部api等。是@Component註解的一種具體形式。

@Repository
此類使用在class上宣告此類用於訪問資料庫,一般作為DAO的角色。

此註解有自動翻譯的特性,例如:當此種component丟擲了一個異常,那麼會有一個handler來處理此異常,無需使用try-catch塊。

五. 資料訪問註解

@Transactional
此註解使用在介面定義、介面中的方法、類定義或者類中的public方法上。需要注意的是此註解並不啟用事務行為,它僅僅是一個元資料,會被一些執行時基礎設施來消費。

六. 任務執行、排程註解

@Scheduled
此註解使用在方法上,宣告此方法被定時排程。使用了此註解的方法返回型別需要是Void,並且不能接受任何引數。

  1. @Scheduled(fixedDelay=1000)

  2. publicvoid schedule() {

  3. }

  4. @Scheduled(fixedRate=1000)

  5. publicvoid schedulg() {

  6. }

第二個與第一個不同之處在於其不會等待上一次的任務執行結束。

@Async
此註解使用在方法上,宣告此方法會在一個單獨的執行緒中執行。不同於Scheduled註解,此註解可以接受引數。

使用此註解的方法的返回型別可以是Void也可是返回值。但是返回值的型別必須是一個Future。

七. 測試註解

@ContextConfiguration
此註解使用在Class上,宣告測試使用的配置檔案,此外,也可以指定載入上下文的類。

此註解一般需要搭配SpringJUnit4ClassRunner使用。

    1. @RunWith(SpringJUnit4ClassRunner.class)

    2. @ContextConfiguration(classes = SpringCoreConfig.class)

    3. publicclassUserServiceTest{

    4. }